channel.go 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038
  1. package controller
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "strconv"
  7. "strings"
  8. "github.com/QuantumNous/new-api/common"
  9. "github.com/QuantumNous/new-api/constant"
  10. "github.com/QuantumNous/new-api/dto"
  11. "github.com/QuantumNous/new-api/model"
  12. "github.com/QuantumNous/new-api/relay/channel/gemini"
  13. "github.com/QuantumNous/new-api/relay/channel/ollama"
  14. "github.com/QuantumNous/new-api/service"
  15. "github.com/gin-gonic/gin"
  16. )
  17. type OpenAIModel struct {
  18. ID string `json:"id"`
  19. Object string `json:"object"`
  20. Created int64 `json:"created"`
  21. OwnedBy string `json:"owned_by"`
  22. Metadata map[string]any `json:"metadata,omitempty"`
  23. Permission []struct {
  24. ID string `json:"id"`
  25. Object string `json:"object"`
  26. Created int64 `json:"created"`
  27. AllowCreateEngine bool `json:"allow_create_engine"`
  28. AllowSampling bool `json:"allow_sampling"`
  29. AllowLogprobs bool `json:"allow_logprobs"`
  30. AllowSearchIndices bool `json:"allow_search_indices"`
  31. AllowView bool `json:"allow_view"`
  32. AllowFineTuning bool `json:"allow_fine_tuning"`
  33. Organization string `json:"organization"`
  34. Group string `json:"group"`
  35. IsBlocking bool `json:"is_blocking"`
  36. } `json:"permission"`
  37. Root string `json:"root"`
  38. Parent string `json:"parent"`
  39. }
  40. type OpenAIModelsResponse struct {
  41. Data []OpenAIModel `json:"data"`
  42. Success bool `json:"success"`
  43. }
  44. func parseStatusFilter(statusParam string) int {
  45. switch strings.ToLower(statusParam) {
  46. case "enabled", "1":
  47. return common.ChannelStatusEnabled
  48. case "disabled", "0":
  49. return 0
  50. default:
  51. return -1
  52. }
  53. }
  54. func clearChannelInfo(channel *model.Channel) {
  55. if channel.ChannelInfo.IsMultiKey {
  56. channel.ChannelInfo.MultiKeyDisabledReason = nil
  57. channel.ChannelInfo.MultiKeyDisabledTime = nil
  58. }
  59. }
  60. func GetAllChannels(c *gin.Context) {
  61. pageInfo := common.GetPageQuery(c)
  62. channelData := make([]*model.Channel, 0)
  63. idSort, _ := strconv.ParseBool(c.Query("id_sort"))
  64. enableTagMode, _ := strconv.ParseBool(c.Query("tag_mode"))
  65. statusParam := c.Query("status")
  66. // statusFilter: -1 all, 1 enabled, 0 disabled (include auto & manual)
  67. statusFilter := parseStatusFilter(statusParam)
  68. // type filter
  69. typeStr := c.Query("type")
  70. typeFilter := -1
  71. if typeStr != "" {
  72. if t, err := strconv.Atoi(typeStr); err == nil {
  73. typeFilter = t
  74. }
  75. }
  76. var total int64
  77. if enableTagMode {
  78. tags, err := model.GetPaginatedTags(pageInfo.GetStartIdx(), pageInfo.GetPageSize())
  79. if err != nil {
  80. c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
  81. return
  82. }
  83. for _, tag := range tags {
  84. if tag == nil || *tag == "" {
  85. continue
  86. }
  87. tagChannels, err := model.GetChannelsByTag(*tag, idSort, false)
  88. if err != nil {
  89. continue
  90. }
  91. filtered := make([]*model.Channel, 0)
  92. for _, ch := range tagChannels {
  93. if statusFilter == common.ChannelStatusEnabled && ch.Status != common.ChannelStatusEnabled {
  94. continue
  95. }
  96. if statusFilter == 0 && ch.Status == common.ChannelStatusEnabled {
  97. continue
  98. }
  99. if typeFilter >= 0 && ch.Type != typeFilter {
  100. continue
  101. }
  102. filtered = append(filtered, ch)
  103. }
  104. channelData = append(channelData, filtered...)
  105. }
  106. total, _ = model.CountAllTags()
  107. } else {
  108. baseQuery := model.DB.Model(&model.Channel{})
  109. if typeFilter >= 0 {
  110. baseQuery = baseQuery.Where("type = ?", typeFilter)
  111. }
  112. if statusFilter == common.ChannelStatusEnabled {
  113. baseQuery = baseQuery.Where("status = ?", common.ChannelStatusEnabled)
  114. } else if statusFilter == 0 {
  115. baseQuery = baseQuery.Where("status != ?", common.ChannelStatusEnabled)
  116. }
  117. baseQuery.Count(&total)
  118. order := "priority desc"
  119. if idSort {
  120. order = "id desc"
  121. }
  122. err := baseQuery.Order(order).Limit(pageInfo.GetPageSize()).Offset(pageInfo.GetStartIdx()).Omit("key").Find(&channelData).Error
  123. if err != nil {
  124. c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
  125. return
  126. }
  127. }
  128. for _, datum := range channelData {
  129. clearChannelInfo(datum)
  130. }
  131. countQuery := model.DB.Model(&model.Channel{})
  132. if statusFilter == common.ChannelStatusEnabled {
  133. countQuery = countQuery.Where("status = ?", common.ChannelStatusEnabled)
  134. } else if statusFilter == 0 {
  135. countQuery = countQuery.Where("status != ?", common.ChannelStatusEnabled)
  136. }
  137. var results []struct {
  138. Type int64
  139. Count int64
  140. }
  141. _ = countQuery.Select("type, count(*) as count").Group("type").Find(&results).Error
  142. typeCounts := make(map[int64]int64)
  143. for _, r := range results {
  144. typeCounts[r.Type] = r.Count
  145. }
  146. common.ApiSuccess(c, gin.H{
  147. "items": channelData,
  148. "total": total,
  149. "page": pageInfo.GetPage(),
  150. "page_size": pageInfo.GetPageSize(),
  151. "type_counts": typeCounts,
  152. })
  153. return
  154. }
  155. func buildFetchModelsHeaders(channel *model.Channel, key string) (http.Header, error) {
  156. var headers http.Header
  157. switch channel.Type {
  158. case constant.ChannelTypeAnthropic:
  159. headers = GetClaudeAuthHeader(key)
  160. default:
  161. headers = GetAuthHeader(key)
  162. }
  163. headerOverride := channel.GetHeaderOverride()
  164. for k, v := range headerOverride {
  165. str, ok := v.(string)
  166. if !ok {
  167. return nil, fmt.Errorf("invalid header override for key %s", k)
  168. }
  169. if strings.Contains(str, "{api_key}") {
  170. str = strings.ReplaceAll(str, "{api_key}", key)
  171. }
  172. headers.Set(k, str)
  173. }
  174. return headers, nil
  175. }
  176. func FetchUpstreamModels(c *gin.Context) {
  177. id, err := strconv.Atoi(c.Param("id"))
  178. if err != nil {
  179. common.ApiError(c, err)
  180. return
  181. }
  182. channel, err := model.GetChannelById(id, true)
  183. if err != nil {
  184. common.ApiError(c, err)
  185. return
  186. }
  187. baseURL := constant.ChannelBaseURLs[channel.Type]
  188. if channel.GetBaseURL() != "" {
  189. baseURL = channel.GetBaseURL()
  190. }
  191. // 对于 Ollama 渠道,使用特殊处理
  192. if channel.Type == constant.ChannelTypeOllama {
  193. key := strings.Split(channel.Key, "\n")[0]
  194. models, err := ollama.FetchOllamaModels(baseURL, key)
  195. if err != nil {
  196. c.JSON(http.StatusOK, gin.H{
  197. "success": false,
  198. "message": fmt.Sprintf("获取Ollama模型失败: %s", err.Error()),
  199. })
  200. return
  201. }
  202. result := OpenAIModelsResponse{
  203. Data: make([]OpenAIModel, 0, len(models)),
  204. }
  205. for _, modelInfo := range models {
  206. metadata := map[string]any{}
  207. if modelInfo.Size > 0 {
  208. metadata["size"] = modelInfo.Size
  209. }
  210. if modelInfo.Digest != "" {
  211. metadata["digest"] = modelInfo.Digest
  212. }
  213. if modelInfo.ModifiedAt != "" {
  214. metadata["modified_at"] = modelInfo.ModifiedAt
  215. }
  216. details := modelInfo.Details
  217. if details.ParentModel != "" || details.Format != "" || details.Family != "" || len(details.Families) > 0 || details.ParameterSize != "" || details.QuantizationLevel != "" {
  218. metadata["details"] = modelInfo.Details
  219. }
  220. if len(metadata) == 0 {
  221. metadata = nil
  222. }
  223. result.Data = append(result.Data, OpenAIModel{
  224. ID: modelInfo.Name,
  225. Object: "model",
  226. Created: 0,
  227. OwnedBy: "ollama",
  228. Metadata: metadata,
  229. })
  230. }
  231. c.JSON(http.StatusOK, gin.H{
  232. "success": true,
  233. "data": result.Data,
  234. })
  235. return
  236. }
  237. // 对于 Gemini 渠道,使用特殊处理
  238. if channel.Type == constant.ChannelTypeGemini {
  239. // 获取用于请求的可用密钥(多密钥渠道优先使用启用状态的密钥)
  240. key, _, apiErr := channel.GetNextEnabledKey()
  241. if apiErr != nil {
  242. c.JSON(http.StatusOK, gin.H{
  243. "success": false,
  244. "message": fmt.Sprintf("获取渠道密钥失败: %s", apiErr.Error()),
  245. })
  246. return
  247. }
  248. key = strings.TrimSpace(key)
  249. models, err := gemini.FetchGeminiModels(baseURL, key, channel.GetSetting().Proxy)
  250. if err != nil {
  251. c.JSON(http.StatusOK, gin.H{
  252. "success": false,
  253. "message": fmt.Sprintf("获取Gemini模型失败: %s", err.Error()),
  254. })
  255. return
  256. }
  257. c.JSON(http.StatusOK, gin.H{
  258. "success": true,
  259. "message": "",
  260. "data": models,
  261. })
  262. return
  263. }
  264. var url string
  265. switch channel.Type {
  266. case constant.ChannelTypeAli:
  267. url = fmt.Sprintf("%s/compatible-mode/v1/models", baseURL)
  268. case constant.ChannelTypeZhipu_v4:
  269. if plan, ok := constant.ChannelSpecialBases[baseURL]; ok && plan.OpenAIBaseURL != "" {
  270. url = fmt.Sprintf("%s/models", plan.OpenAIBaseURL)
  271. } else {
  272. url = fmt.Sprintf("%s/api/paas/v4/models", baseURL)
  273. }
  274. case constant.ChannelTypeVolcEngine:
  275. if plan, ok := constant.ChannelSpecialBases[baseURL]; ok && plan.OpenAIBaseURL != "" {
  276. url = fmt.Sprintf("%s/v1/models", plan.OpenAIBaseURL)
  277. } else {
  278. url = fmt.Sprintf("%s/v1/models", baseURL)
  279. }
  280. case constant.ChannelTypeMoonshot:
  281. if plan, ok := constant.ChannelSpecialBases[baseURL]; ok && plan.OpenAIBaseURL != "" {
  282. url = fmt.Sprintf("%s/models", plan.OpenAIBaseURL)
  283. } else {
  284. url = fmt.Sprintf("%s/v1/models", baseURL)
  285. }
  286. default:
  287. url = fmt.Sprintf("%s/v1/models", baseURL)
  288. }
  289. // 获取用于请求的可用密钥(多密钥渠道优先使用启用状态的密钥)
  290. key, _, apiErr := channel.GetNextEnabledKey()
  291. if apiErr != nil {
  292. c.JSON(http.StatusOK, gin.H{
  293. "success": false,
  294. "message": fmt.Sprintf("获取渠道密钥失败: %s", apiErr.Error()),
  295. })
  296. return
  297. }
  298. key = strings.TrimSpace(key)
  299. headers, err := buildFetchModelsHeaders(channel, key)
  300. if err != nil {
  301. common.ApiError(c, err)
  302. return
  303. }
  304. body, err := GetResponseBody("GET", url, channel, headers)
  305. if err != nil {
  306. common.ApiError(c, err)
  307. return
  308. }
  309. var result OpenAIModelsResponse
  310. if err = json.Unmarshal(body, &result); err != nil {
  311. c.JSON(http.StatusOK, gin.H{
  312. "success": false,
  313. "message": fmt.Sprintf("解析响应失败: %s", err.Error()),
  314. })
  315. return
  316. }
  317. var ids []string
  318. for _, model := range result.Data {
  319. id := model.ID
  320. if channel.Type == constant.ChannelTypeGemini {
  321. id = strings.TrimPrefix(id, "models/")
  322. }
  323. ids = append(ids, id)
  324. }
  325. c.JSON(http.StatusOK, gin.H{
  326. "success": true,
  327. "message": "",
  328. "data": ids,
  329. })
  330. }
  331. func FixChannelsAbilities(c *gin.Context) {
  332. success, fails, err := model.FixAbility()
  333. if err != nil {
  334. common.ApiError(c, err)
  335. return
  336. }
  337. c.JSON(http.StatusOK, gin.H{
  338. "success": true,
  339. "message": "",
  340. "data": gin.H{
  341. "success": success,
  342. "fails": fails,
  343. },
  344. })
  345. }
  346. func SearchChannels(c *gin.Context) {
  347. keyword := c.Query("keyword")
  348. group := c.Query("group")
  349. modelKeyword := c.Query("model")
  350. statusParam := c.Query("status")
  351. statusFilter := parseStatusFilter(statusParam)
  352. idSort, _ := strconv.ParseBool(c.Query("id_sort"))
  353. enableTagMode, _ := strconv.ParseBool(c.Query("tag_mode"))
  354. channelData := make([]*model.Channel, 0)
  355. if enableTagMode {
  356. tags, err := model.SearchTags(keyword, group, modelKeyword, idSort)
  357. if err != nil {
  358. c.JSON(http.StatusOK, gin.H{
  359. "success": false,
  360. "message": err.Error(),
  361. })
  362. return
  363. }
  364. for _, tag := range tags {
  365. if tag != nil && *tag != "" {
  366. tagChannel, err := model.GetChannelsByTag(*tag, idSort, false)
  367. if err == nil {
  368. channelData = append(channelData, tagChannel...)
  369. }
  370. }
  371. }
  372. } else {
  373. channels, err := model.SearchChannels(keyword, group, modelKeyword, idSort)
  374. if err != nil {
  375. c.JSON(http.StatusOK, gin.H{
  376. "success": false,
  377. "message": err.Error(),
  378. })
  379. return
  380. }
  381. channelData = channels
  382. }
  383. if statusFilter == common.ChannelStatusEnabled || statusFilter == 0 {
  384. filtered := make([]*model.Channel, 0, len(channelData))
  385. for _, ch := range channelData {
  386. if statusFilter == common.ChannelStatusEnabled && ch.Status != common.ChannelStatusEnabled {
  387. continue
  388. }
  389. if statusFilter == 0 && ch.Status == common.ChannelStatusEnabled {
  390. continue
  391. }
  392. filtered = append(filtered, ch)
  393. }
  394. channelData = filtered
  395. }
  396. // calculate type counts for search results
  397. typeCounts := make(map[int64]int64)
  398. for _, channel := range channelData {
  399. typeCounts[int64(channel.Type)]++
  400. }
  401. typeParam := c.Query("type")
  402. typeFilter := -1
  403. if typeParam != "" {
  404. if tp, err := strconv.Atoi(typeParam); err == nil {
  405. typeFilter = tp
  406. }
  407. }
  408. if typeFilter >= 0 {
  409. filtered := make([]*model.Channel, 0, len(channelData))
  410. for _, ch := range channelData {
  411. if ch.Type == typeFilter {
  412. filtered = append(filtered, ch)
  413. }
  414. }
  415. channelData = filtered
  416. }
  417. page, _ := strconv.Atoi(c.DefaultQuery("p", "1"))
  418. pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
  419. if page < 1 {
  420. page = 1
  421. }
  422. if pageSize <= 0 {
  423. pageSize = 20
  424. }
  425. total := len(channelData)
  426. startIdx := (page - 1) * pageSize
  427. if startIdx > total {
  428. startIdx = total
  429. }
  430. endIdx := startIdx + pageSize
  431. if endIdx > total {
  432. endIdx = total
  433. }
  434. pagedData := channelData[startIdx:endIdx]
  435. for _, datum := range pagedData {
  436. clearChannelInfo(datum)
  437. }
  438. c.JSON(http.StatusOK, gin.H{
  439. "success": true,
  440. "message": "",
  441. "data": gin.H{
  442. "items": pagedData,
  443. "total": total,
  444. "type_counts": typeCounts,
  445. },
  446. })
  447. return
  448. }
  449. func GetChannel(c *gin.Context) {
  450. id, err := strconv.Atoi(c.Param("id"))
  451. if err != nil {
  452. common.ApiError(c, err)
  453. return
  454. }
  455. channel, err := model.GetChannelById(id, false)
  456. if err != nil {
  457. common.ApiError(c, err)
  458. return
  459. }
  460. if channel != nil {
  461. clearChannelInfo(channel)
  462. }
  463. c.JSON(http.StatusOK, gin.H{
  464. "success": true,
  465. "message": "",
  466. "data": channel,
  467. })
  468. return
  469. }
  470. // GetChannelKey 获取渠道密钥(需要通过安全验证中间件)
  471. // 此函数依赖 SecureVerificationRequired 中间件,确保用户已通过安全验证
  472. func GetChannelKey(c *gin.Context) {
  473. userId := c.GetInt("id")
  474. channelId, err := strconv.Atoi(c.Param("id"))
  475. if err != nil {
  476. common.ApiError(c, fmt.Errorf("渠道ID格式错误: %v", err))
  477. return
  478. }
  479. // 获取渠道信息(包含密钥)
  480. channel, err := model.GetChannelById(channelId, true)
  481. if err != nil {
  482. common.ApiError(c, fmt.Errorf("获取渠道信息失败: %v", err))
  483. return
  484. }
  485. if channel == nil {
  486. common.ApiError(c, fmt.Errorf("渠道不存在"))
  487. return
  488. }
  489. // 记录操作日志
  490. model.RecordLog(userId, model.LogTypeSystem, fmt.Sprintf("查看渠道密钥信息 (渠道ID: %d)", channelId))
  491. // 返回渠道密钥
  492. c.JSON(http.StatusOK, gin.H{
  493. "success": true,
  494. "message": "获取成功",
  495. "data": map[string]interface{}{
  496. "key": channel.Key,
  497. },
  498. })
  499. }
  500. // validateTwoFactorAuth 统一的2FA验证函数
  501. func validateTwoFactorAuth(twoFA *model.TwoFA, code string) bool {
  502. // 尝试验证TOTP
  503. if cleanCode, err := common.ValidateNumericCode(code); err == nil {
  504. if isValid, _ := twoFA.ValidateTOTPAndUpdateUsage(cleanCode); isValid {
  505. return true
  506. }
  507. }
  508. // 尝试验证备用码
  509. if isValid, err := twoFA.ValidateBackupCodeAndUpdateUsage(code); err == nil && isValid {
  510. return true
  511. }
  512. return false
  513. }
  514. // validateChannel 通用的渠道校验函数
  515. func validateChannel(channel *model.Channel, isAdd bool) error {
  516. // 校验 channel settings
  517. if err := channel.ValidateSettings(); err != nil {
  518. return fmt.Errorf("渠道额外设置[channel setting] 格式错误:%s", err.Error())
  519. }
  520. // 如果是添加操作,检查 channel 和 key 是否为空
  521. if isAdd {
  522. if channel == nil || channel.Key == "" {
  523. return fmt.Errorf("channel cannot be empty")
  524. }
  525. // 检查模型名称长度是否超过 255
  526. for _, m := range channel.GetModels() {
  527. if len(m) > 255 {
  528. return fmt.Errorf("模型名称过长: %s", m)
  529. }
  530. }
  531. }
  532. // VertexAI 特殊校验
  533. if channel.Type == constant.ChannelTypeVertexAi {
  534. if channel.Other == "" {
  535. return fmt.Errorf("部署地区不能为空")
  536. }
  537. regionMap, err := common.StrToMap(channel.Other)
  538. if err != nil {
  539. return fmt.Errorf("部署地区必须是标准的Json格式,例如{\"default\": \"us-central1\", \"region2\": \"us-east1\"}")
  540. }
  541. if regionMap["default"] == nil {
  542. return fmt.Errorf("部署地区必须包含default字段")
  543. }
  544. }
  545. return nil
  546. }
  547. type AddChannelRequest struct {
  548. Mode string `json:"mode"`
  549. MultiKeyMode constant.MultiKeyMode `json:"multi_key_mode"`
  550. BatchAddSetKeyPrefix2Name bool `json:"batch_add_set_key_prefix_2_name"`
  551. Channel *model.Channel `json:"channel"`
  552. }
  553. func getVertexArrayKeys(keys string) ([]string, error) {
  554. if keys == "" {
  555. return nil, nil
  556. }
  557. var keyArray []interface{}
  558. err := common.Unmarshal([]byte(keys), &keyArray)
  559. if err != nil {
  560. return nil, fmt.Errorf("批量添加 Vertex AI 必须使用标准的JsonArray格式,例如[{key1}, {key2}...],请检查输入: %w", err)
  561. }
  562. cleanKeys := make([]string, 0, len(keyArray))
  563. for _, key := range keyArray {
  564. var keyStr string
  565. switch v := key.(type) {
  566. case string:
  567. keyStr = strings.TrimSpace(v)
  568. default:
  569. bytes, err := json.Marshal(v)
  570. if err != nil {
  571. return nil, fmt.Errorf("Vertex AI key JSON 编码失败: %w", err)
  572. }
  573. keyStr = string(bytes)
  574. }
  575. if keyStr != "" {
  576. cleanKeys = append(cleanKeys, keyStr)
  577. }
  578. }
  579. if len(cleanKeys) == 0 {
  580. return nil, fmt.Errorf("批量添加 Vertex AI 的 keys 不能为空")
  581. }
  582. return cleanKeys, nil
  583. }
  584. func AddChannel(c *gin.Context) {
  585. addChannelRequest := AddChannelRequest{}
  586. err := c.ShouldBindJSON(&addChannelRequest)
  587. if err != nil {
  588. common.ApiError(c, err)
  589. return
  590. }
  591. // 使用统一的校验函数
  592. if err := validateChannel(addChannelRequest.Channel, true); err != nil {
  593. c.JSON(http.StatusOK, gin.H{
  594. "success": false,
  595. "message": err.Error(),
  596. })
  597. return
  598. }
  599. addChannelRequest.Channel.CreatedTime = common.GetTimestamp()
  600. keys := make([]string, 0)
  601. switch addChannelRequest.Mode {
  602. case "multi_to_single":
  603. addChannelRequest.Channel.ChannelInfo.IsMultiKey = true
  604. addChannelRequest.Channel.ChannelInfo.MultiKeyMode = addChannelRequest.MultiKeyMode
  605. if addChannelRequest.Channel.Type == constant.ChannelTypeVertexAi && addChannelRequest.Channel.GetOtherSettings().VertexKeyType != dto.VertexKeyTypeAPIKey {
  606. array, err := getVertexArrayKeys(addChannelRequest.Channel.Key)
  607. if err != nil {
  608. c.JSON(http.StatusOK, gin.H{
  609. "success": false,
  610. "message": err.Error(),
  611. })
  612. return
  613. }
  614. addChannelRequest.Channel.ChannelInfo.MultiKeySize = len(array)
  615. addChannelRequest.Channel.Key = strings.Join(array, "\n")
  616. } else {
  617. cleanKeys := make([]string, 0)
  618. for _, key := range strings.Split(addChannelRequest.Channel.Key, "\n") {
  619. if key == "" {
  620. continue
  621. }
  622. key = strings.TrimSpace(key)
  623. cleanKeys = append(cleanKeys, key)
  624. }
  625. addChannelRequest.Channel.ChannelInfo.MultiKeySize = len(cleanKeys)
  626. addChannelRequest.Channel.Key = strings.Join(cleanKeys, "\n")
  627. }
  628. keys = []string{addChannelRequest.Channel.Key}
  629. case "batch":
  630. if addChannelRequest.Channel.Type == constant.ChannelTypeVertexAi && addChannelRequest.Channel.GetOtherSettings().VertexKeyType != dto.VertexKeyTypeAPIKey {
  631. // multi json
  632. keys, err = getVertexArrayKeys(addChannelRequest.Channel.Key)
  633. if err != nil {
  634. c.JSON(http.StatusOK, gin.H{
  635. "success": false,
  636. "message": err.Error(),
  637. })
  638. return
  639. }
  640. } else {
  641. keys = strings.Split(addChannelRequest.Channel.Key, "\n")
  642. }
  643. case "single":
  644. keys = []string{addChannelRequest.Channel.Key}
  645. default:
  646. c.JSON(http.StatusOK, gin.H{
  647. "success": false,
  648. "message": "不支持的添加模式",
  649. })
  650. return
  651. }
  652. channels := make([]model.Channel, 0, len(keys))
  653. for _, key := range keys {
  654. if key == "" {
  655. continue
  656. }
  657. localChannel := addChannelRequest.Channel
  658. localChannel.Key = key
  659. if addChannelRequest.BatchAddSetKeyPrefix2Name && len(keys) > 1 {
  660. keyPrefix := localChannel.Key
  661. if len(localChannel.Key) > 8 {
  662. keyPrefix = localChannel.Key[:8]
  663. }
  664. localChannel.Name = fmt.Sprintf("%s %s", localChannel.Name, keyPrefix)
  665. }
  666. channels = append(channels, *localChannel)
  667. }
  668. err = model.BatchInsertChannels(channels)
  669. if err != nil {
  670. common.ApiError(c, err)
  671. return
  672. }
  673. service.ResetProxyClientCache()
  674. c.JSON(http.StatusOK, gin.H{
  675. "success": true,
  676. "message": "",
  677. })
  678. return
  679. }
  680. func DeleteChannel(c *gin.Context) {
  681. id, _ := strconv.Atoi(c.Param("id"))
  682. channel := model.Channel{Id: id}
  683. err := channel.Delete()
  684. if err != nil {
  685. common.ApiError(c, err)
  686. return
  687. }
  688. model.InitChannelCache()
  689. c.JSON(http.StatusOK, gin.H{
  690. "success": true,
  691. "message": "",
  692. })
  693. return
  694. }
  695. func DeleteDisabledChannel(c *gin.Context) {
  696. rows, err := model.DeleteDisabledChannel()
  697. if err != nil {
  698. common.ApiError(c, err)
  699. return
  700. }
  701. model.InitChannelCache()
  702. c.JSON(http.StatusOK, gin.H{
  703. "success": true,
  704. "message": "",
  705. "data": rows,
  706. })
  707. return
  708. }
  709. type ChannelTag struct {
  710. Tag string `json:"tag"`
  711. NewTag *string `json:"new_tag"`
  712. Priority *int64 `json:"priority"`
  713. Weight *uint `json:"weight"`
  714. ModelMapping *string `json:"model_mapping"`
  715. Models *string `json:"models"`
  716. Groups *string `json:"groups"`
  717. ParamOverride *string `json:"param_override"`
  718. HeaderOverride *string `json:"header_override"`
  719. }
  720. func DisableTagChannels(c *gin.Context) {
  721. channelTag := ChannelTag{}
  722. err := c.ShouldBindJSON(&channelTag)
  723. if err != nil || channelTag.Tag == "" {
  724. c.JSON(http.StatusOK, gin.H{
  725. "success": false,
  726. "message": "参数错误",
  727. })
  728. return
  729. }
  730. err = model.DisableChannelByTag(channelTag.Tag)
  731. if err != nil {
  732. common.ApiError(c, err)
  733. return
  734. }
  735. model.InitChannelCache()
  736. c.JSON(http.StatusOK, gin.H{
  737. "success": true,
  738. "message": "",
  739. })
  740. return
  741. }
  742. func EnableTagChannels(c *gin.Context) {
  743. channelTag := ChannelTag{}
  744. err := c.ShouldBindJSON(&channelTag)
  745. if err != nil || channelTag.Tag == "" {
  746. c.JSON(http.StatusOK, gin.H{
  747. "success": false,
  748. "message": "参数错误",
  749. })
  750. return
  751. }
  752. err = model.EnableChannelByTag(channelTag.Tag)
  753. if err != nil {
  754. common.ApiError(c, err)
  755. return
  756. }
  757. model.InitChannelCache()
  758. c.JSON(http.StatusOK, gin.H{
  759. "success": true,
  760. "message": "",
  761. })
  762. return
  763. }
  764. func EditTagChannels(c *gin.Context) {
  765. channelTag := ChannelTag{}
  766. err := c.ShouldBindJSON(&channelTag)
  767. if err != nil {
  768. c.JSON(http.StatusOK, gin.H{
  769. "success": false,
  770. "message": "参数错误",
  771. })
  772. return
  773. }
  774. if channelTag.Tag == "" {
  775. c.JSON(http.StatusOK, gin.H{
  776. "success": false,
  777. "message": "tag不能为空",
  778. })
  779. return
  780. }
  781. if channelTag.ParamOverride != nil {
  782. trimmed := strings.TrimSpace(*channelTag.ParamOverride)
  783. if trimmed != "" && !json.Valid([]byte(trimmed)) {
  784. c.JSON(http.StatusOK, gin.H{
  785. "success": false,
  786. "message": "参数覆盖必须是合法的 JSON 格式",
  787. })
  788. return
  789. }
  790. channelTag.ParamOverride = common.GetPointer[string](trimmed)
  791. }
  792. if channelTag.HeaderOverride != nil {
  793. trimmed := strings.TrimSpace(*channelTag.HeaderOverride)
  794. if trimmed != "" && !json.Valid([]byte(trimmed)) {
  795. c.JSON(http.StatusOK, gin.H{
  796. "success": false,
  797. "message": "请求头覆盖必须是合法的 JSON 格式",
  798. })
  799. return
  800. }
  801. channelTag.HeaderOverride = common.GetPointer[string](trimmed)
  802. }
  803. err = model.EditChannelByTag(channelTag.Tag, channelTag.NewTag, channelTag.ModelMapping, channelTag.Models, channelTag.Groups, channelTag.Priority, channelTag.Weight, channelTag.ParamOverride, channelTag.HeaderOverride)
  804. if err != nil {
  805. common.ApiError(c, err)
  806. return
  807. }
  808. model.InitChannelCache()
  809. c.JSON(http.StatusOK, gin.H{
  810. "success": true,
  811. "message": "",
  812. })
  813. return
  814. }
  815. type ChannelBatch struct {
  816. Ids []int `json:"ids"`
  817. Tag *string `json:"tag"`
  818. }
  819. func DeleteChannelBatch(c *gin.Context) {
  820. channelBatch := ChannelBatch{}
  821. err := c.ShouldBindJSON(&channelBatch)
  822. if err != nil || len(channelBatch.Ids) == 0 {
  823. c.JSON(http.StatusOK, gin.H{
  824. "success": false,
  825. "message": "参数错误",
  826. })
  827. return
  828. }
  829. err = model.BatchDeleteChannels(channelBatch.Ids)
  830. if err != nil {
  831. common.ApiError(c, err)
  832. return
  833. }
  834. model.InitChannelCache()
  835. c.JSON(http.StatusOK, gin.H{
  836. "success": true,
  837. "message": "",
  838. "data": len(channelBatch.Ids),
  839. })
  840. return
  841. }
  842. type PatchChannel struct {
  843. model.Channel
  844. MultiKeyMode *string `json:"multi_key_mode"`
  845. KeyMode *string `json:"key_mode"` // 多key模式下密钥覆盖或者追加
  846. }
  847. func UpdateChannel(c *gin.Context) {
  848. channel := PatchChannel{}
  849. err := c.ShouldBindJSON(&channel)
  850. if err != nil {
  851. common.ApiError(c, err)
  852. return
  853. }
  854. // 使用统一的校验函数
  855. if err := validateChannel(&channel.Channel, false); err != nil {
  856. c.JSON(http.StatusOK, gin.H{
  857. "success": false,
  858. "message": err.Error(),
  859. })
  860. return
  861. }
  862. // Preserve existing ChannelInfo to ensure multi-key channels keep correct state even if the client does not send ChannelInfo in the request.
  863. originChannel, err := model.GetChannelById(channel.Id, true)
  864. if err != nil {
  865. c.JSON(http.StatusOK, gin.H{
  866. "success": false,
  867. "message": err.Error(),
  868. })
  869. return
  870. }
  871. // Always copy the original ChannelInfo so that fields like IsMultiKey and MultiKeySize are retained.
  872. channel.ChannelInfo = originChannel.ChannelInfo
  873. // If the request explicitly specifies a new MultiKeyMode, apply it on top of the original info.
  874. if channel.MultiKeyMode != nil && *channel.MultiKeyMode != "" {
  875. channel.ChannelInfo.MultiKeyMode = constant.MultiKeyMode(*channel.MultiKeyMode)
  876. }
  877. // 处理多key模式下的密钥追加/覆盖逻辑
  878. if channel.KeyMode != nil && channel.ChannelInfo.IsMultiKey {
  879. switch *channel.KeyMode {
  880. case "append":
  881. // 追加模式:将新密钥添加到现有密钥列表
  882. if originChannel.Key != "" {
  883. var newKeys []string
  884. var existingKeys []string
  885. // 解析现有密钥
  886. if strings.HasPrefix(strings.TrimSpace(originChannel.Key), "[") {
  887. // JSON数组格式
  888. var arr []json.RawMessage
  889. if err := json.Unmarshal([]byte(strings.TrimSpace(originChannel.Key)), &arr); err == nil {
  890. existingKeys = make([]string, len(arr))
  891. for i, v := range arr {
  892. existingKeys[i] = string(v)
  893. }
  894. }
  895. } else {
  896. // 换行分隔格式
  897. existingKeys = strings.Split(strings.Trim(originChannel.Key, "\n"), "\n")
  898. }
  899. // 处理 Vertex AI 的特殊情况
  900. if channel.Type == constant.ChannelTypeVertexAi && channel.GetOtherSettings().VertexKeyType != dto.VertexKeyTypeAPIKey {
  901. // 尝试解析新密钥为JSON数组
  902. if strings.HasPrefix(strings.TrimSpace(channel.Key), "[") {
  903. array, err := getVertexArrayKeys(channel.Key)
  904. if err != nil {
  905. c.JSON(http.StatusOK, gin.H{
  906. "success": false,
  907. "message": "追加密钥解析失败: " + err.Error(),
  908. })
  909. return
  910. }
  911. newKeys = array
  912. } else {
  913. // 单个JSON密钥
  914. newKeys = []string{channel.Key}
  915. }
  916. } else {
  917. // 普通渠道的处理
  918. inputKeys := strings.Split(channel.Key, "\n")
  919. for _, key := range inputKeys {
  920. key = strings.TrimSpace(key)
  921. if key != "" {
  922. newKeys = append(newKeys, key)
  923. }
  924. }
  925. }
  926. seen := make(map[string]struct{}, len(existingKeys)+len(newKeys))
  927. for _, key := range existingKeys {
  928. normalized := strings.TrimSpace(key)
  929. if normalized == "" {
  930. continue
  931. }
  932. seen[normalized] = struct{}{}
  933. }
  934. dedupedNewKeys := make([]string, 0, len(newKeys))
  935. for _, key := range newKeys {
  936. normalized := strings.TrimSpace(key)
  937. if normalized == "" {
  938. continue
  939. }
  940. if _, ok := seen[normalized]; ok {
  941. continue
  942. }
  943. seen[normalized] = struct{}{}
  944. dedupedNewKeys = append(dedupedNewKeys, normalized)
  945. }
  946. allKeys := append(existingKeys, dedupedNewKeys...)
  947. channel.Key = strings.Join(allKeys, "\n")
  948. }
  949. case "replace":
  950. // 覆盖模式:直接使用新密钥(默认行为,不需要特殊处理)
  951. }
  952. }
  953. err = channel.Update()
  954. if err != nil {
  955. common.ApiError(c, err)
  956. return
  957. }
  958. model.InitChannelCache()
  959. service.ResetProxyClientCache()
  960. channel.Key = ""
  961. clearChannelInfo(&channel.Channel)
  962. c.JSON(http.StatusOK, gin.H{
  963. "success": true,
  964. "message": "",
  965. "data": channel,
  966. })
  967. return
  968. }
  969. func FetchModels(c *gin.Context) {
  970. var req struct {
  971. BaseURL string `json:"base_url"`
  972. Type int `json:"type"`
  973. Key string `json:"key"`
  974. }
  975. if err := c.ShouldBindJSON(&req); err != nil {
  976. c.JSON(http.StatusBadRequest, gin.H{
  977. "success": false,
  978. "message": "Invalid request",
  979. })
  980. return
  981. }
  982. baseURL := req.BaseURL
  983. if baseURL == "" {
  984. baseURL = constant.ChannelBaseURLs[req.Type]
  985. }
  986. // remove line breaks and extra spaces.
  987. key := strings.TrimSpace(req.Key)
  988. key = strings.Split(key, "\n")[0]
  989. if req.Type == constant.ChannelTypeOllama {
  990. models, err := ollama.FetchOllamaModels(baseURL, key)
  991. if err != nil {
  992. c.JSON(http.StatusOK, gin.H{
  993. "success": false,
  994. "message": fmt.Sprintf("获取Ollama模型失败: %s", err.Error()),
  995. })
  996. return
  997. }
  998. names := make([]string, 0, len(models))
  999. for _, modelInfo := range models {
  1000. names = append(names, modelInfo.Name)
  1001. }
  1002. c.JSON(http.StatusOK, gin.H{
  1003. "success": true,
  1004. "data": names,
  1005. })
  1006. return
  1007. }
  1008. if req.Type == constant.ChannelTypeGemini {
  1009. models, err := gemini.FetchGeminiModels(baseURL, key, "")
  1010. if err != nil {
  1011. c.JSON(http.StatusOK, gin.H{
  1012. "success": false,
  1013. "message": fmt.Sprintf("获取Gemini模型失败: %s", err.Error()),
  1014. })
  1015. return
  1016. }
  1017. c.JSON(http.StatusOK, gin.H{
  1018. "success": true,
  1019. "data": models,
  1020. })
  1021. return
  1022. }
  1023. client := &http.Client{}
  1024. url := fmt.Sprintf("%s/v1/models", baseURL)
  1025. request, err := http.NewRequest("GET", url, nil)
  1026. if err != nil {
  1027. c.JSON(http.StatusInternalServerError, gin.H{
  1028. "success": false,
  1029. "message": err.Error(),
  1030. })
  1031. return
  1032. }
  1033. request.Header.Set("Authorization", "Bearer "+key)
  1034. response, err := client.Do(request)
  1035. if err != nil {
  1036. c.JSON(http.StatusInternalServerError, gin.H{
  1037. "success": false,
  1038. "message": err.Error(),
  1039. })
  1040. return
  1041. }
  1042. //check status code
  1043. if response.StatusCode != http.StatusOK {
  1044. c.JSON(http.StatusInternalServerError, gin.H{
  1045. "success": false,
  1046. "message": "Failed to fetch models",
  1047. })
  1048. return
  1049. }
  1050. defer response.Body.Close()
  1051. var result struct {
  1052. Data []struct {
  1053. ID string `json:"id"`
  1054. } `json:"data"`
  1055. }
  1056. if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
  1057. c.JSON(http.StatusInternalServerError, gin.H{
  1058. "success": false,
  1059. "message": err.Error(),
  1060. })
  1061. return
  1062. }
  1063. var models []string
  1064. for _, model := range result.Data {
  1065. models = append(models, model.ID)
  1066. }
  1067. c.JSON(http.StatusOK, gin.H{
  1068. "success": true,
  1069. "data": models,
  1070. })
  1071. }
  1072. func BatchSetChannelTag(c *gin.Context) {
  1073. channelBatch := ChannelBatch{}
  1074. err := c.ShouldBindJSON(&channelBatch)
  1075. if err != nil || len(channelBatch.Ids) == 0 {
  1076. c.JSON(http.StatusOK, gin.H{
  1077. "success": false,
  1078. "message": "参数错误",
  1079. })
  1080. return
  1081. }
  1082. err = model.BatchSetChannelTag(channelBatch.Ids, channelBatch.Tag)
  1083. if err != nil {
  1084. common.ApiError(c, err)
  1085. return
  1086. }
  1087. model.InitChannelCache()
  1088. c.JSON(http.StatusOK, gin.H{
  1089. "success": true,
  1090. "message": "",
  1091. "data": len(channelBatch.Ids),
  1092. })
  1093. return
  1094. }
  1095. func GetTagModels(c *gin.Context) {
  1096. tag := c.Query("tag")
  1097. if tag == "" {
  1098. c.JSON(http.StatusBadRequest, gin.H{
  1099. "success": false,
  1100. "message": "tag不能为空",
  1101. })
  1102. return
  1103. }
  1104. channels, err := model.GetChannelsByTag(tag, false, false) // idSort=false, selectAll=false
  1105. if err != nil {
  1106. c.JSON(http.StatusInternalServerError, gin.H{
  1107. "success": false,
  1108. "message": err.Error(),
  1109. })
  1110. return
  1111. }
  1112. var longestModels string
  1113. maxLength := 0
  1114. // Find the longest models string among all channels with the given tag
  1115. for _, channel := range channels {
  1116. if channel.Models != "" {
  1117. currentModels := strings.Split(channel.Models, ",")
  1118. if len(currentModels) > maxLength {
  1119. maxLength = len(currentModels)
  1120. longestModels = channel.Models
  1121. }
  1122. }
  1123. }
  1124. c.JSON(http.StatusOK, gin.H{
  1125. "success": true,
  1126. "message": "",
  1127. "data": longestModels,
  1128. })
  1129. return
  1130. }
  1131. // CopyChannel handles cloning an existing channel with its key.
  1132. // POST /api/channel/copy/:id
  1133. // Optional query params:
  1134. //
  1135. // suffix - string appended to the original name (default "_复制")
  1136. // reset_balance - bool, when true will reset balance & used_quota to 0 (default true)
  1137. func CopyChannel(c *gin.Context) {
  1138. id, err := strconv.Atoi(c.Param("id"))
  1139. if err != nil {
  1140. c.JSON(http.StatusOK, gin.H{"success": false, "message": "invalid id"})
  1141. return
  1142. }
  1143. suffix := c.DefaultQuery("suffix", "_复制")
  1144. resetBalance := true
  1145. if rbStr := c.DefaultQuery("reset_balance", "true"); rbStr != "" {
  1146. if v, err := strconv.ParseBool(rbStr); err == nil {
  1147. resetBalance = v
  1148. }
  1149. }
  1150. // fetch original channel with key
  1151. origin, err := model.GetChannelById(id, true)
  1152. if err != nil {
  1153. c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
  1154. return
  1155. }
  1156. // clone channel
  1157. clone := *origin // shallow copy is sufficient as we will overwrite primitives
  1158. clone.Id = 0 // let DB auto-generate
  1159. clone.CreatedTime = common.GetTimestamp()
  1160. clone.Name = origin.Name + suffix
  1161. clone.TestTime = 0
  1162. clone.ResponseTime = 0
  1163. if resetBalance {
  1164. clone.Balance = 0
  1165. clone.UsedQuota = 0
  1166. }
  1167. // insert
  1168. if err := model.BatchInsertChannels([]model.Channel{clone}); err != nil {
  1169. c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
  1170. return
  1171. }
  1172. model.InitChannelCache()
  1173. // success
  1174. c.JSON(http.StatusOK, gin.H{"success": true, "message": "", "data": gin.H{"id": clone.Id}})
  1175. }
  1176. // MultiKeyManageRequest represents the request for multi-key management operations
  1177. type MultiKeyManageRequest struct {
  1178. ChannelId int `json:"channel_id"`
  1179. Action string `json:"action"` // "disable_key", "enable_key", "delete_key", "delete_disabled_keys", "get_key_status"
  1180. KeyIndex *int `json:"key_index,omitempty"` // for disable_key, enable_key, and delete_key actions
  1181. Page int `json:"page,omitempty"` // for get_key_status pagination
  1182. PageSize int `json:"page_size,omitempty"` // for get_key_status pagination
  1183. Status *int `json:"status,omitempty"` // for get_key_status filtering: 1=enabled, 2=manual_disabled, 3=auto_disabled, nil=all
  1184. }
  1185. // MultiKeyStatusResponse represents the response for key status query
  1186. type MultiKeyStatusResponse struct {
  1187. Keys []KeyStatus `json:"keys"`
  1188. Total int `json:"total"`
  1189. Page int `json:"page"`
  1190. PageSize int `json:"page_size"`
  1191. TotalPages int `json:"total_pages"`
  1192. // Statistics
  1193. EnabledCount int `json:"enabled_count"`
  1194. ManualDisabledCount int `json:"manual_disabled_count"`
  1195. AutoDisabledCount int `json:"auto_disabled_count"`
  1196. }
  1197. type KeyStatus struct {
  1198. Index int `json:"index"`
  1199. Status int `json:"status"` // 1: enabled, 2: disabled
  1200. DisabledTime int64 `json:"disabled_time,omitempty"`
  1201. Reason string `json:"reason,omitempty"`
  1202. KeyPreview string `json:"key_preview"` // first 10 chars of key for identification
  1203. }
  1204. // ManageMultiKeys handles multi-key management operations
  1205. func ManageMultiKeys(c *gin.Context) {
  1206. request := MultiKeyManageRequest{}
  1207. err := c.ShouldBindJSON(&request)
  1208. if err != nil {
  1209. common.ApiError(c, err)
  1210. return
  1211. }
  1212. channel, err := model.GetChannelById(request.ChannelId, true)
  1213. if err != nil {
  1214. c.JSON(http.StatusOK, gin.H{
  1215. "success": false,
  1216. "message": "渠道不存在",
  1217. })
  1218. return
  1219. }
  1220. if !channel.ChannelInfo.IsMultiKey {
  1221. c.JSON(http.StatusOK, gin.H{
  1222. "success": false,
  1223. "message": "该渠道不是多密钥模式",
  1224. })
  1225. return
  1226. }
  1227. lock := model.GetChannelPollingLock(channel.Id)
  1228. lock.Lock()
  1229. defer lock.Unlock()
  1230. switch request.Action {
  1231. case "get_key_status":
  1232. keys := channel.GetKeys()
  1233. // Default pagination parameters
  1234. page := request.Page
  1235. pageSize := request.PageSize
  1236. if page <= 0 {
  1237. page = 1
  1238. }
  1239. if pageSize <= 0 {
  1240. pageSize = 50 // Default page size
  1241. }
  1242. // Statistics for all keys (unchanged by filtering)
  1243. var enabledCount, manualDisabledCount, autoDisabledCount int
  1244. // Build all key status data first
  1245. var allKeyStatusList []KeyStatus
  1246. for i, key := range keys {
  1247. status := 1 // default enabled
  1248. var disabledTime int64
  1249. var reason string
  1250. if channel.ChannelInfo.MultiKeyStatusList != nil {
  1251. if s, exists := channel.ChannelInfo.MultiKeyStatusList[i]; exists {
  1252. status = s
  1253. }
  1254. }
  1255. // Count for statistics (all keys)
  1256. switch status {
  1257. case 1:
  1258. enabledCount++
  1259. case 2:
  1260. manualDisabledCount++
  1261. case 3:
  1262. autoDisabledCount++
  1263. }
  1264. if status != 1 {
  1265. if channel.ChannelInfo.MultiKeyDisabledTime != nil {
  1266. disabledTime = channel.ChannelInfo.MultiKeyDisabledTime[i]
  1267. }
  1268. if channel.ChannelInfo.MultiKeyDisabledReason != nil {
  1269. reason = channel.ChannelInfo.MultiKeyDisabledReason[i]
  1270. }
  1271. }
  1272. // Create key preview (first 10 chars)
  1273. keyPreview := key
  1274. if len(key) > 10 {
  1275. keyPreview = key[:10] + "..."
  1276. }
  1277. allKeyStatusList = append(allKeyStatusList, KeyStatus{
  1278. Index: i,
  1279. Status: status,
  1280. DisabledTime: disabledTime,
  1281. Reason: reason,
  1282. KeyPreview: keyPreview,
  1283. })
  1284. }
  1285. // Apply status filter if specified
  1286. var filteredKeyStatusList []KeyStatus
  1287. if request.Status != nil {
  1288. for _, keyStatus := range allKeyStatusList {
  1289. if keyStatus.Status == *request.Status {
  1290. filteredKeyStatusList = append(filteredKeyStatusList, keyStatus)
  1291. }
  1292. }
  1293. } else {
  1294. filteredKeyStatusList = allKeyStatusList
  1295. }
  1296. // Calculate pagination based on filtered results
  1297. filteredTotal := len(filteredKeyStatusList)
  1298. totalPages := (filteredTotal + pageSize - 1) / pageSize
  1299. if totalPages == 0 {
  1300. totalPages = 1
  1301. }
  1302. if page > totalPages {
  1303. page = totalPages
  1304. }
  1305. // Calculate range for current page
  1306. start := (page - 1) * pageSize
  1307. end := start + pageSize
  1308. if end > filteredTotal {
  1309. end = filteredTotal
  1310. }
  1311. // Get the page data
  1312. var pageKeyStatusList []KeyStatus
  1313. if start < filteredTotal {
  1314. pageKeyStatusList = filteredKeyStatusList[start:end]
  1315. }
  1316. c.JSON(http.StatusOK, gin.H{
  1317. "success": true,
  1318. "message": "",
  1319. "data": MultiKeyStatusResponse{
  1320. Keys: pageKeyStatusList,
  1321. Total: filteredTotal, // Total of filtered results
  1322. Page: page,
  1323. PageSize: pageSize,
  1324. TotalPages: totalPages,
  1325. EnabledCount: enabledCount, // Overall statistics
  1326. ManualDisabledCount: manualDisabledCount, // Overall statistics
  1327. AutoDisabledCount: autoDisabledCount, // Overall statistics
  1328. },
  1329. })
  1330. return
  1331. case "disable_key":
  1332. if request.KeyIndex == nil {
  1333. c.JSON(http.StatusOK, gin.H{
  1334. "success": false,
  1335. "message": "未指定要禁用的密钥索引",
  1336. })
  1337. return
  1338. }
  1339. keyIndex := *request.KeyIndex
  1340. if keyIndex < 0 || keyIndex >= channel.ChannelInfo.MultiKeySize {
  1341. c.JSON(http.StatusOK, gin.H{
  1342. "success": false,
  1343. "message": "密钥索引超出范围",
  1344. })
  1345. return
  1346. }
  1347. if channel.ChannelInfo.MultiKeyStatusList == nil {
  1348. channel.ChannelInfo.MultiKeyStatusList = make(map[int]int)
  1349. }
  1350. if channel.ChannelInfo.MultiKeyDisabledTime == nil {
  1351. channel.ChannelInfo.MultiKeyDisabledTime = make(map[int]int64)
  1352. }
  1353. if channel.ChannelInfo.MultiKeyDisabledReason == nil {
  1354. channel.ChannelInfo.MultiKeyDisabledReason = make(map[int]string)
  1355. }
  1356. channel.ChannelInfo.MultiKeyStatusList[keyIndex] = 2 // disabled
  1357. err = channel.Update()
  1358. if err != nil {
  1359. common.ApiError(c, err)
  1360. return
  1361. }
  1362. model.InitChannelCache()
  1363. c.JSON(http.StatusOK, gin.H{
  1364. "success": true,
  1365. "message": "密钥已禁用",
  1366. })
  1367. return
  1368. case "enable_key":
  1369. if request.KeyIndex == nil {
  1370. c.JSON(http.StatusOK, gin.H{
  1371. "success": false,
  1372. "message": "未指定要启用的密钥索引",
  1373. })
  1374. return
  1375. }
  1376. keyIndex := *request.KeyIndex
  1377. if keyIndex < 0 || keyIndex >= channel.ChannelInfo.MultiKeySize {
  1378. c.JSON(http.StatusOK, gin.H{
  1379. "success": false,
  1380. "message": "密钥索引超出范围",
  1381. })
  1382. return
  1383. }
  1384. // 从状态列表中删除该密钥的记录,使其回到默认启用状态
  1385. if channel.ChannelInfo.MultiKeyStatusList != nil {
  1386. delete(channel.ChannelInfo.MultiKeyStatusList, keyIndex)
  1387. }
  1388. if channel.ChannelInfo.MultiKeyDisabledTime != nil {
  1389. delete(channel.ChannelInfo.MultiKeyDisabledTime, keyIndex)
  1390. }
  1391. if channel.ChannelInfo.MultiKeyDisabledReason != nil {
  1392. delete(channel.ChannelInfo.MultiKeyDisabledReason, keyIndex)
  1393. }
  1394. err = channel.Update()
  1395. if err != nil {
  1396. common.ApiError(c, err)
  1397. return
  1398. }
  1399. model.InitChannelCache()
  1400. c.JSON(http.StatusOK, gin.H{
  1401. "success": true,
  1402. "message": "密钥已启用",
  1403. })
  1404. return
  1405. case "enable_all_keys":
  1406. // 清空所有禁用状态,使所有密钥回到默认启用状态
  1407. var enabledCount int
  1408. if channel.ChannelInfo.MultiKeyStatusList != nil {
  1409. enabledCount = len(channel.ChannelInfo.MultiKeyStatusList)
  1410. }
  1411. channel.ChannelInfo.MultiKeyStatusList = make(map[int]int)
  1412. channel.ChannelInfo.MultiKeyDisabledTime = make(map[int]int64)
  1413. channel.ChannelInfo.MultiKeyDisabledReason = make(map[int]string)
  1414. err = channel.Update()
  1415. if err != nil {
  1416. common.ApiError(c, err)
  1417. return
  1418. }
  1419. model.InitChannelCache()
  1420. c.JSON(http.StatusOK, gin.H{
  1421. "success": true,
  1422. "message": fmt.Sprintf("已启用 %d 个密钥", enabledCount),
  1423. })
  1424. return
  1425. case "disable_all_keys":
  1426. // 禁用所有启用的密钥
  1427. if channel.ChannelInfo.MultiKeyStatusList == nil {
  1428. channel.ChannelInfo.MultiKeyStatusList = make(map[int]int)
  1429. }
  1430. if channel.ChannelInfo.MultiKeyDisabledTime == nil {
  1431. channel.ChannelInfo.MultiKeyDisabledTime = make(map[int]int64)
  1432. }
  1433. if channel.ChannelInfo.MultiKeyDisabledReason == nil {
  1434. channel.ChannelInfo.MultiKeyDisabledReason = make(map[int]string)
  1435. }
  1436. var disabledCount int
  1437. for i := 0; i < channel.ChannelInfo.MultiKeySize; i++ {
  1438. status := 1 // default enabled
  1439. if s, exists := channel.ChannelInfo.MultiKeyStatusList[i]; exists {
  1440. status = s
  1441. }
  1442. // 只禁用当前启用的密钥
  1443. if status == 1 {
  1444. channel.ChannelInfo.MultiKeyStatusList[i] = 2 // disabled
  1445. disabledCount++
  1446. }
  1447. }
  1448. if disabledCount == 0 {
  1449. c.JSON(http.StatusOK, gin.H{
  1450. "success": false,
  1451. "message": "没有可禁用的密钥",
  1452. })
  1453. return
  1454. }
  1455. err = channel.Update()
  1456. if err != nil {
  1457. common.ApiError(c, err)
  1458. return
  1459. }
  1460. model.InitChannelCache()
  1461. c.JSON(http.StatusOK, gin.H{
  1462. "success": true,
  1463. "message": fmt.Sprintf("已禁用 %d 个密钥", disabledCount),
  1464. })
  1465. return
  1466. case "delete_key":
  1467. if request.KeyIndex == nil {
  1468. c.JSON(http.StatusOK, gin.H{
  1469. "success": false,
  1470. "message": "未指定要删除的密钥索引",
  1471. })
  1472. return
  1473. }
  1474. keyIndex := *request.KeyIndex
  1475. if keyIndex < 0 || keyIndex >= channel.ChannelInfo.MultiKeySize {
  1476. c.JSON(http.StatusOK, gin.H{
  1477. "success": false,
  1478. "message": "密钥索引超出范围",
  1479. })
  1480. return
  1481. }
  1482. keys := channel.GetKeys()
  1483. var remainingKeys []string
  1484. var newStatusList = make(map[int]int)
  1485. var newDisabledTime = make(map[int]int64)
  1486. var newDisabledReason = make(map[int]string)
  1487. newIndex := 0
  1488. for i, key := range keys {
  1489. // 跳过要删除的密钥
  1490. if i == keyIndex {
  1491. continue
  1492. }
  1493. remainingKeys = append(remainingKeys, key)
  1494. // 保留其他密钥的状态信息,重新索引
  1495. if channel.ChannelInfo.MultiKeyStatusList != nil {
  1496. if status, exists := channel.ChannelInfo.MultiKeyStatusList[i]; exists && status != 1 {
  1497. newStatusList[newIndex] = status
  1498. }
  1499. }
  1500. if channel.ChannelInfo.MultiKeyDisabledTime != nil {
  1501. if t, exists := channel.ChannelInfo.MultiKeyDisabledTime[i]; exists {
  1502. newDisabledTime[newIndex] = t
  1503. }
  1504. }
  1505. if channel.ChannelInfo.MultiKeyDisabledReason != nil {
  1506. if r, exists := channel.ChannelInfo.MultiKeyDisabledReason[i]; exists {
  1507. newDisabledReason[newIndex] = r
  1508. }
  1509. }
  1510. newIndex++
  1511. }
  1512. if len(remainingKeys) == 0 {
  1513. c.JSON(http.StatusOK, gin.H{
  1514. "success": false,
  1515. "message": "不能删除最后一个密钥",
  1516. })
  1517. return
  1518. }
  1519. // Update channel with remaining keys
  1520. channel.Key = strings.Join(remainingKeys, "\n")
  1521. channel.ChannelInfo.MultiKeySize = len(remainingKeys)
  1522. channel.ChannelInfo.MultiKeyStatusList = newStatusList
  1523. channel.ChannelInfo.MultiKeyDisabledTime = newDisabledTime
  1524. channel.ChannelInfo.MultiKeyDisabledReason = newDisabledReason
  1525. err = channel.Update()
  1526. if err != nil {
  1527. common.ApiError(c, err)
  1528. return
  1529. }
  1530. model.InitChannelCache()
  1531. c.JSON(http.StatusOK, gin.H{
  1532. "success": true,
  1533. "message": "密钥已删除",
  1534. })
  1535. return
  1536. case "delete_disabled_keys":
  1537. keys := channel.GetKeys()
  1538. var remainingKeys []string
  1539. var deletedCount int
  1540. var newStatusList = make(map[int]int)
  1541. var newDisabledTime = make(map[int]int64)
  1542. var newDisabledReason = make(map[int]string)
  1543. newIndex := 0
  1544. for i, key := range keys {
  1545. status := 1 // default enabled
  1546. if channel.ChannelInfo.MultiKeyStatusList != nil {
  1547. if s, exists := channel.ChannelInfo.MultiKeyStatusList[i]; exists {
  1548. status = s
  1549. }
  1550. }
  1551. // 只删除自动禁用(status == 3)的密钥,保留启用(status == 1)和手动禁用(status == 2)的密钥
  1552. if status == 3 {
  1553. deletedCount++
  1554. } else {
  1555. remainingKeys = append(remainingKeys, key)
  1556. // 保留非自动禁用密钥的状态信息,重新索引
  1557. if status != 1 {
  1558. newStatusList[newIndex] = status
  1559. if channel.ChannelInfo.MultiKeyDisabledTime != nil {
  1560. if t, exists := channel.ChannelInfo.MultiKeyDisabledTime[i]; exists {
  1561. newDisabledTime[newIndex] = t
  1562. }
  1563. }
  1564. if channel.ChannelInfo.MultiKeyDisabledReason != nil {
  1565. if r, exists := channel.ChannelInfo.MultiKeyDisabledReason[i]; exists {
  1566. newDisabledReason[newIndex] = r
  1567. }
  1568. }
  1569. }
  1570. newIndex++
  1571. }
  1572. }
  1573. if deletedCount == 0 {
  1574. c.JSON(http.StatusOK, gin.H{
  1575. "success": false,
  1576. "message": "没有需要删除的自动禁用密钥",
  1577. })
  1578. return
  1579. }
  1580. // Update channel with remaining keys
  1581. channel.Key = strings.Join(remainingKeys, "\n")
  1582. channel.ChannelInfo.MultiKeySize = len(remainingKeys)
  1583. channel.ChannelInfo.MultiKeyStatusList = newStatusList
  1584. channel.ChannelInfo.MultiKeyDisabledTime = newDisabledTime
  1585. channel.ChannelInfo.MultiKeyDisabledReason = newDisabledReason
  1586. err = channel.Update()
  1587. if err != nil {
  1588. common.ApiError(c, err)
  1589. return
  1590. }
  1591. model.InitChannelCache()
  1592. c.JSON(http.StatusOK, gin.H{
  1593. "success": true,
  1594. "message": fmt.Sprintf("已删除 %d 个自动禁用的密钥", deletedCount),
  1595. "data": deletedCount,
  1596. })
  1597. return
  1598. default:
  1599. c.JSON(http.StatusOK, gin.H{
  1600. "success": false,
  1601. "message": "不支持的操作",
  1602. })
  1603. return
  1604. }
  1605. }
  1606. // OllamaPullModel 拉取 Ollama 模型
  1607. func OllamaPullModel(c *gin.Context) {
  1608. var req struct {
  1609. ChannelID int `json:"channel_id"`
  1610. ModelName string `json:"model_name"`
  1611. }
  1612. if err := c.ShouldBindJSON(&req); err != nil {
  1613. c.JSON(http.StatusBadRequest, gin.H{
  1614. "success": false,
  1615. "message": "Invalid request parameters",
  1616. })
  1617. return
  1618. }
  1619. if req.ChannelID == 0 || req.ModelName == "" {
  1620. c.JSON(http.StatusBadRequest, gin.H{
  1621. "success": false,
  1622. "message": "Channel ID and model name are required",
  1623. })
  1624. return
  1625. }
  1626. // 获取渠道信息
  1627. channel, err := model.GetChannelById(req.ChannelID, true)
  1628. if err != nil {
  1629. c.JSON(http.StatusNotFound, gin.H{
  1630. "success": false,
  1631. "message": "Channel not found",
  1632. })
  1633. return
  1634. }
  1635. // 检查是否是 Ollama 渠道
  1636. if channel.Type != constant.ChannelTypeOllama {
  1637. c.JSON(http.StatusBadRequest, gin.H{
  1638. "success": false,
  1639. "message": "This operation is only supported for Ollama channels",
  1640. })
  1641. return
  1642. }
  1643. baseURL := constant.ChannelBaseURLs[channel.Type]
  1644. if channel.GetBaseURL() != "" {
  1645. baseURL = channel.GetBaseURL()
  1646. }
  1647. key := strings.Split(channel.Key, "\n")[0]
  1648. err = ollama.PullOllamaModel(baseURL, key, req.ModelName)
  1649. if err != nil {
  1650. c.JSON(http.StatusInternalServerError, gin.H{
  1651. "success": false,
  1652. "message": fmt.Sprintf("Failed to pull model: %s", err.Error()),
  1653. })
  1654. return
  1655. }
  1656. c.JSON(http.StatusOK, gin.H{
  1657. "success": true,
  1658. "message": fmt.Sprintf("Model %s pulled successfully", req.ModelName),
  1659. })
  1660. }
  1661. // OllamaPullModelStream 流式拉取 Ollama 模型
  1662. func OllamaPullModelStream(c *gin.Context) {
  1663. var req struct {
  1664. ChannelID int `json:"channel_id"`
  1665. ModelName string `json:"model_name"`
  1666. }
  1667. if err := c.ShouldBindJSON(&req); err != nil {
  1668. c.JSON(http.StatusBadRequest, gin.H{
  1669. "success": false,
  1670. "message": "Invalid request parameters",
  1671. })
  1672. return
  1673. }
  1674. if req.ChannelID == 0 || req.ModelName == "" {
  1675. c.JSON(http.StatusBadRequest, gin.H{
  1676. "success": false,
  1677. "message": "Channel ID and model name are required",
  1678. })
  1679. return
  1680. }
  1681. // 获取渠道信息
  1682. channel, err := model.GetChannelById(req.ChannelID, true)
  1683. if err != nil {
  1684. c.JSON(http.StatusNotFound, gin.H{
  1685. "success": false,
  1686. "message": "Channel not found",
  1687. })
  1688. return
  1689. }
  1690. // 检查是否是 Ollama 渠道
  1691. if channel.Type != constant.ChannelTypeOllama {
  1692. c.JSON(http.StatusBadRequest, gin.H{
  1693. "success": false,
  1694. "message": "This operation is only supported for Ollama channels",
  1695. })
  1696. return
  1697. }
  1698. baseURL := constant.ChannelBaseURLs[channel.Type]
  1699. if channel.GetBaseURL() != "" {
  1700. baseURL = channel.GetBaseURL()
  1701. }
  1702. // 设置 SSE 头部
  1703. c.Header("Content-Type", "text/event-stream")
  1704. c.Header("Cache-Control", "no-cache")
  1705. c.Header("Connection", "keep-alive")
  1706. c.Header("Access-Control-Allow-Origin", "*")
  1707. key := strings.Split(channel.Key, "\n")[0]
  1708. // 创建进度回调函数
  1709. progressCallback := func(progress ollama.OllamaPullResponse) {
  1710. data, _ := json.Marshal(progress)
  1711. fmt.Fprintf(c.Writer, "data: %s\n\n", string(data))
  1712. c.Writer.Flush()
  1713. }
  1714. // 执行拉取
  1715. err = ollama.PullOllamaModelStream(baseURL, key, req.ModelName, progressCallback)
  1716. if err != nil {
  1717. errorData, _ := json.Marshal(gin.H{
  1718. "error": err.Error(),
  1719. })
  1720. fmt.Fprintf(c.Writer, "data: %s\n\n", string(errorData))
  1721. } else {
  1722. successData, _ := json.Marshal(gin.H{
  1723. "message": fmt.Sprintf("Model %s pulled successfully", req.ModelName),
  1724. })
  1725. fmt.Fprintf(c.Writer, "data: %s\n\n", string(successData))
  1726. }
  1727. // 发送结束标志
  1728. fmt.Fprintf(c.Writer, "data: [DONE]\n\n")
  1729. c.Writer.Flush()
  1730. }
  1731. // OllamaDeleteModel 删除 Ollama 模型
  1732. func OllamaDeleteModel(c *gin.Context) {
  1733. var req struct {
  1734. ChannelID int `json:"channel_id"`
  1735. ModelName string `json:"model_name"`
  1736. }
  1737. if err := c.ShouldBindJSON(&req); err != nil {
  1738. c.JSON(http.StatusBadRequest, gin.H{
  1739. "success": false,
  1740. "message": "Invalid request parameters",
  1741. })
  1742. return
  1743. }
  1744. if req.ChannelID == 0 || req.ModelName == "" {
  1745. c.JSON(http.StatusBadRequest, gin.H{
  1746. "success": false,
  1747. "message": "Channel ID and model name are required",
  1748. })
  1749. return
  1750. }
  1751. // 获取渠道信息
  1752. channel, err := model.GetChannelById(req.ChannelID, true)
  1753. if err != nil {
  1754. c.JSON(http.StatusNotFound, gin.H{
  1755. "success": false,
  1756. "message": "Channel not found",
  1757. })
  1758. return
  1759. }
  1760. // 检查是否是 Ollama 渠道
  1761. if channel.Type != constant.ChannelTypeOllama {
  1762. c.JSON(http.StatusBadRequest, gin.H{
  1763. "success": false,
  1764. "message": "This operation is only supported for Ollama channels",
  1765. })
  1766. return
  1767. }
  1768. baseURL := constant.ChannelBaseURLs[channel.Type]
  1769. if channel.GetBaseURL() != "" {
  1770. baseURL = channel.GetBaseURL()
  1771. }
  1772. key := strings.Split(channel.Key, "\n")[0]
  1773. err = ollama.DeleteOllamaModel(baseURL, key, req.ModelName)
  1774. if err != nil {
  1775. c.JSON(http.StatusInternalServerError, gin.H{
  1776. "success": false,
  1777. "message": fmt.Sprintf("Failed to delete model: %s", err.Error()),
  1778. })
  1779. return
  1780. }
  1781. c.JSON(http.StatusOK, gin.H{
  1782. "success": true,
  1783. "message": fmt.Sprintf("Model %s deleted successfully", req.ModelName),
  1784. })
  1785. }
  1786. // OllamaVersion 获取 Ollama 服务版本信息
  1787. func OllamaVersion(c *gin.Context) {
  1788. id, err := strconv.Atoi(c.Param("id"))
  1789. if err != nil {
  1790. c.JSON(http.StatusBadRequest, gin.H{
  1791. "success": false,
  1792. "message": "Invalid channel id",
  1793. })
  1794. return
  1795. }
  1796. channel, err := model.GetChannelById(id, true)
  1797. if err != nil {
  1798. c.JSON(http.StatusNotFound, gin.H{
  1799. "success": false,
  1800. "message": "Channel not found",
  1801. })
  1802. return
  1803. }
  1804. if channel.Type != constant.ChannelTypeOllama {
  1805. c.JSON(http.StatusBadRequest, gin.H{
  1806. "success": false,
  1807. "message": "This operation is only supported for Ollama channels",
  1808. })
  1809. return
  1810. }
  1811. baseURL := constant.ChannelBaseURLs[channel.Type]
  1812. if channel.GetBaseURL() != "" {
  1813. baseURL = channel.GetBaseURL()
  1814. }
  1815. key := strings.Split(channel.Key, "\n")[0]
  1816. version, err := ollama.FetchOllamaVersion(baseURL, key)
  1817. if err != nil {
  1818. c.JSON(http.StatusOK, gin.H{
  1819. "success": false,
  1820. "message": fmt.Sprintf("获取Ollama版本失败: %s", err.Error()),
  1821. })
  1822. return
  1823. }
  1824. c.JSON(http.StatusOK, gin.H{
  1825. "success": true,
  1826. "data": gin.H{
  1827. "version": version,
  1828. },
  1829. })
  1830. }