channel.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. package controller
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "one-api/common"
  7. "one-api/model"
  8. "strconv"
  9. "strings"
  10. "github.com/gin-gonic/gin"
  11. )
  12. type OpenAIModel struct {
  13. ID string `json:"id"`
  14. Object string `json:"object"`
  15. Created int64 `json:"created"`
  16. OwnedBy string `json:"owned_by"`
  17. Permission []struct {
  18. ID string `json:"id"`
  19. Object string `json:"object"`
  20. Created int64 `json:"created"`
  21. AllowCreateEngine bool `json:"allow_create_engine"`
  22. AllowSampling bool `json:"allow_sampling"`
  23. AllowLogprobs bool `json:"allow_logprobs"`
  24. AllowSearchIndices bool `json:"allow_search_indices"`
  25. AllowView bool `json:"allow_view"`
  26. AllowFineTuning bool `json:"allow_fine_tuning"`
  27. Organization string `json:"organization"`
  28. Group string `json:"group"`
  29. IsBlocking bool `json:"is_blocking"`
  30. } `json:"permission"`
  31. Root string `json:"root"`
  32. Parent string `json:"parent"`
  33. }
  34. type OpenAIModelsResponse struct {
  35. Data []OpenAIModel `json:"data"`
  36. Success bool `json:"success"`
  37. }
  38. func GetAllChannels(c *gin.Context) {
  39. p, _ := strconv.Atoi(c.Query("p"))
  40. pageSize, _ := strconv.Atoi(c.Query("page_size"))
  41. if p < 0 {
  42. p = 0
  43. }
  44. if pageSize < 0 {
  45. pageSize = common.ItemsPerPage
  46. }
  47. channelData := make([]*model.Channel, 0)
  48. idSort, _ := strconv.ParseBool(c.Query("id_sort"))
  49. enableTagMode, _ := strconv.ParseBool(c.Query("tag_mode"))
  50. if enableTagMode {
  51. tags, err := model.GetPaginatedTags(p*pageSize, pageSize)
  52. if err != nil {
  53. c.JSON(http.StatusOK, gin.H{
  54. "success": false,
  55. "message": err.Error(),
  56. })
  57. return
  58. }
  59. for _, tag := range tags {
  60. if tag != nil && *tag != "" {
  61. tagChannel, err := model.GetChannelsByTag(*tag, idSort)
  62. if err == nil {
  63. channelData = append(channelData, tagChannel...)
  64. }
  65. }
  66. }
  67. } else {
  68. channels, err := model.GetAllChannels(p*pageSize, pageSize, false, idSort)
  69. if err != nil {
  70. c.JSON(http.StatusOK, gin.H{
  71. "success": false,
  72. "message": err.Error(),
  73. })
  74. return
  75. }
  76. channelData = channels
  77. }
  78. c.JSON(http.StatusOK, gin.H{
  79. "success": true,
  80. "message": "",
  81. "data": channelData,
  82. })
  83. return
  84. }
  85. func FetchUpstreamModels(c *gin.Context) {
  86. id, err := strconv.Atoi(c.Param("id"))
  87. if err != nil {
  88. c.JSON(http.StatusOK, gin.H{
  89. "success": false,
  90. "message": err.Error(),
  91. })
  92. return
  93. }
  94. channel, err := model.GetChannelById(id, true)
  95. if err != nil {
  96. c.JSON(http.StatusOK, gin.H{
  97. "success": false,
  98. "message": err.Error(),
  99. })
  100. return
  101. }
  102. //if channel.Type != common.ChannelTypeOpenAI {
  103. // c.JSON(http.StatusOK, gin.H{
  104. // "success": false,
  105. // "message": "仅支持 OpenAI 类型渠道",
  106. // })
  107. // return
  108. //}
  109. baseURL := common.ChannelBaseURLs[channel.Type]
  110. if channel.GetBaseURL() != "" {
  111. baseURL = channel.GetBaseURL()
  112. }
  113. url := fmt.Sprintf("%s/v1/models", baseURL)
  114. body, err := GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
  115. if err != nil {
  116. c.JSON(http.StatusOK, gin.H{
  117. "success": false,
  118. "message": err.Error(),
  119. })
  120. return
  121. }
  122. var result OpenAIModelsResponse
  123. if err = json.Unmarshal(body, &result); err != nil {
  124. c.JSON(http.StatusOK, gin.H{
  125. "success": false,
  126. "message": fmt.Sprintf("解析响应失败: %s", err.Error()),
  127. })
  128. return
  129. }
  130. var ids []string
  131. for _, model := range result.Data {
  132. ids = append(ids, model.ID)
  133. }
  134. c.JSON(http.StatusOK, gin.H{
  135. "success": true,
  136. "message": "",
  137. "data": ids,
  138. })
  139. }
  140. func FixChannelsAbilities(c *gin.Context) {
  141. count, err := model.FixAbility()
  142. if err != nil {
  143. c.JSON(http.StatusOK, gin.H{
  144. "success": false,
  145. "message": err.Error(),
  146. })
  147. return
  148. }
  149. c.JSON(http.StatusOK, gin.H{
  150. "success": true,
  151. "message": "",
  152. "data": count,
  153. })
  154. }
  155. func SearchChannels(c *gin.Context) {
  156. keyword := c.Query("keyword")
  157. group := c.Query("group")
  158. modelKeyword := c.Query("model")
  159. idSort, _ := strconv.ParseBool(c.Query("id_sort"))
  160. enableTagMode, _ := strconv.ParseBool(c.Query("tag_mode"))
  161. channelData := make([]*model.Channel, 0)
  162. if enableTagMode {
  163. tags, err := model.SearchTags(keyword, group, modelKeyword, idSort)
  164. if err != nil {
  165. c.JSON(http.StatusOK, gin.H{
  166. "success": false,
  167. "message": err.Error(),
  168. })
  169. return
  170. }
  171. for _, tag := range tags {
  172. if tag != nil && *tag != "" {
  173. tagChannel, err := model.GetChannelsByTag(*tag, idSort)
  174. if err == nil {
  175. channelData = append(channelData, tagChannel...)
  176. }
  177. }
  178. }
  179. } else {
  180. channels, err := model.SearchChannels(keyword, group, modelKeyword, idSort)
  181. if err != nil {
  182. c.JSON(http.StatusOK, gin.H{
  183. "success": false,
  184. "message": err.Error(),
  185. })
  186. return
  187. }
  188. channelData = channels
  189. }
  190. c.JSON(http.StatusOK, gin.H{
  191. "success": true,
  192. "message": "",
  193. "data": channelData,
  194. })
  195. return
  196. }
  197. func GetChannel(c *gin.Context) {
  198. id, err := strconv.Atoi(c.Param("id"))
  199. if err != nil {
  200. c.JSON(http.StatusOK, gin.H{
  201. "success": false,
  202. "message": err.Error(),
  203. })
  204. return
  205. }
  206. channel, err := model.GetChannelById(id, false)
  207. if err != nil {
  208. c.JSON(http.StatusOK, gin.H{
  209. "success": false,
  210. "message": err.Error(),
  211. })
  212. return
  213. }
  214. c.JSON(http.StatusOK, gin.H{
  215. "success": true,
  216. "message": "",
  217. "data": channel,
  218. })
  219. return
  220. }
  221. func AddChannel(c *gin.Context) {
  222. channel := model.Channel{}
  223. err := c.ShouldBindJSON(&channel)
  224. if err != nil {
  225. c.JSON(http.StatusOK, gin.H{
  226. "success": false,
  227. "message": err.Error(),
  228. })
  229. return
  230. }
  231. channel.CreatedTime = common.GetTimestamp()
  232. keys := strings.Split(channel.Key, "\n")
  233. if channel.Type == common.ChannelTypeVertexAi {
  234. if channel.Other == "" {
  235. c.JSON(http.StatusOK, gin.H{
  236. "success": false,
  237. "message": "部署地区不能为空",
  238. })
  239. return
  240. } else {
  241. if common.IsJsonStr(channel.Other) {
  242. // must have default
  243. regionMap := common.StrToMap(channel.Other)
  244. if regionMap["default"] == nil {
  245. c.JSON(http.StatusOK, gin.H{
  246. "success": false,
  247. "message": "部署地区必须包含default字段",
  248. })
  249. return
  250. }
  251. }
  252. }
  253. keys = []string{channel.Key}
  254. }
  255. channels := make([]model.Channel, 0, len(keys))
  256. for _, key := range keys {
  257. if key == "" {
  258. continue
  259. }
  260. localChannel := channel
  261. localChannel.Key = key
  262. channels = append(channels, localChannel)
  263. }
  264. err = model.BatchInsertChannels(channels)
  265. if err != nil {
  266. c.JSON(http.StatusOK, gin.H{
  267. "success": false,
  268. "message": err.Error(),
  269. })
  270. return
  271. }
  272. c.JSON(http.StatusOK, gin.H{
  273. "success": true,
  274. "message": "",
  275. })
  276. return
  277. }
  278. func DeleteChannel(c *gin.Context) {
  279. id, _ := strconv.Atoi(c.Param("id"))
  280. channel := model.Channel{Id: id}
  281. err := channel.Delete()
  282. if err != nil {
  283. c.JSON(http.StatusOK, gin.H{
  284. "success": false,
  285. "message": err.Error(),
  286. })
  287. return
  288. }
  289. c.JSON(http.StatusOK, gin.H{
  290. "success": true,
  291. "message": "",
  292. })
  293. return
  294. }
  295. func DeleteDisabledChannel(c *gin.Context) {
  296. rows, err := model.DeleteDisabledChannel()
  297. if err != nil {
  298. c.JSON(http.StatusOK, gin.H{
  299. "success": false,
  300. "message": err.Error(),
  301. })
  302. return
  303. }
  304. c.JSON(http.StatusOK, gin.H{
  305. "success": true,
  306. "message": "",
  307. "data": rows,
  308. })
  309. return
  310. }
  311. type ChannelTag struct {
  312. Tag string `json:"tag"`
  313. NewTag *string `json:"new_tag"`
  314. Priority *int64 `json:"priority"`
  315. Weight *uint `json:"weight"`
  316. ModelMapping *string `json:"model_mapping"`
  317. Models *string `json:"models"`
  318. Groups *string `json:"groups"`
  319. }
  320. func DisableTagChannels(c *gin.Context) {
  321. channelTag := ChannelTag{}
  322. err := c.ShouldBindJSON(&channelTag)
  323. if err != nil || channelTag.Tag == "" {
  324. c.JSON(http.StatusOK, gin.H{
  325. "success": false,
  326. "message": "参数错误",
  327. })
  328. return
  329. }
  330. err = model.DisableChannelByTag(channelTag.Tag)
  331. if err != nil {
  332. c.JSON(http.StatusOK, gin.H{
  333. "success": false,
  334. "message": err.Error(),
  335. })
  336. return
  337. }
  338. c.JSON(http.StatusOK, gin.H{
  339. "success": true,
  340. "message": "",
  341. })
  342. return
  343. }
  344. func EnableTagChannels(c *gin.Context) {
  345. channelTag := ChannelTag{}
  346. err := c.ShouldBindJSON(&channelTag)
  347. if err != nil || channelTag.Tag == "" {
  348. c.JSON(http.StatusOK, gin.H{
  349. "success": false,
  350. "message": "参数错误",
  351. })
  352. return
  353. }
  354. err = model.EnableChannelByTag(channelTag.Tag)
  355. if err != nil {
  356. c.JSON(http.StatusOK, gin.H{
  357. "success": false,
  358. "message": err.Error(),
  359. })
  360. return
  361. }
  362. c.JSON(http.StatusOK, gin.H{
  363. "success": true,
  364. "message": "",
  365. })
  366. return
  367. }
  368. func EditTagChannels(c *gin.Context) {
  369. channelTag := ChannelTag{}
  370. err := c.ShouldBindJSON(&channelTag)
  371. if err != nil {
  372. c.JSON(http.StatusOK, gin.H{
  373. "success": false,
  374. "message": "参数错误",
  375. })
  376. return
  377. }
  378. if channelTag.Tag == "" {
  379. c.JSON(http.StatusOK, gin.H{
  380. "success": false,
  381. "message": "tag不能为空",
  382. })
  383. return
  384. }
  385. err = model.EditChannelByTag(channelTag.Tag, channelTag.NewTag, channelTag.ModelMapping, channelTag.Models, channelTag.Groups, channelTag.Priority, channelTag.Weight)
  386. if err != nil {
  387. c.JSON(http.StatusOK, gin.H{
  388. "success": false,
  389. "message": err.Error(),
  390. })
  391. return
  392. }
  393. c.JSON(http.StatusOK, gin.H{
  394. "success": true,
  395. "message": "",
  396. })
  397. return
  398. }
  399. type ChannelBatch struct {
  400. Ids []int `json:"ids"`
  401. Tag *string `json:"tag"`
  402. }
  403. func DeleteChannelBatch(c *gin.Context) {
  404. channelBatch := ChannelBatch{}
  405. err := c.ShouldBindJSON(&channelBatch)
  406. if err != nil || len(channelBatch.Ids) == 0 {
  407. c.JSON(http.StatusOK, gin.H{
  408. "success": false,
  409. "message": "参数错误",
  410. })
  411. return
  412. }
  413. err = model.BatchDeleteChannels(channelBatch.Ids)
  414. if err != nil {
  415. c.JSON(http.StatusOK, gin.H{
  416. "success": false,
  417. "message": err.Error(),
  418. })
  419. return
  420. }
  421. c.JSON(http.StatusOK, gin.H{
  422. "success": true,
  423. "message": "",
  424. "data": len(channelBatch.Ids),
  425. })
  426. return
  427. }
  428. func UpdateChannel(c *gin.Context) {
  429. channel := model.Channel{}
  430. err := c.ShouldBindJSON(&channel)
  431. if err != nil {
  432. c.JSON(http.StatusOK, gin.H{
  433. "success": false,
  434. "message": err.Error(),
  435. })
  436. return
  437. }
  438. if channel.Type == common.ChannelTypeVertexAi {
  439. if channel.Other == "" {
  440. c.JSON(http.StatusOK, gin.H{
  441. "success": false,
  442. "message": "部署地区不能为空",
  443. })
  444. return
  445. } else {
  446. if common.IsJsonStr(channel.Other) {
  447. // must have default
  448. regionMap := common.StrToMap(channel.Other)
  449. if regionMap["default"] == nil {
  450. c.JSON(http.StatusOK, gin.H{
  451. "success": false,
  452. "message": "部署地区必须包含default字段",
  453. })
  454. return
  455. }
  456. }
  457. }
  458. }
  459. err = channel.Update()
  460. if err != nil {
  461. c.JSON(http.StatusOK, gin.H{
  462. "success": false,
  463. "message": err.Error(),
  464. })
  465. return
  466. }
  467. c.JSON(http.StatusOK, gin.H{
  468. "success": true,
  469. "message": "",
  470. "data": channel,
  471. })
  472. return
  473. }
  474. func FetchModels(c *gin.Context) {
  475. var req struct {
  476. BaseURL string `json:"base_url"`
  477. Key string `json:"key"`
  478. }
  479. if err := c.ShouldBindJSON(&req); err != nil {
  480. c.JSON(http.StatusBadRequest, gin.H{
  481. "success": false,
  482. "message": "Invalid request",
  483. })
  484. return
  485. }
  486. baseURL := req.BaseURL
  487. if baseURL == "" {
  488. baseURL = "https://api.openai.com"
  489. }
  490. client := &http.Client{}
  491. url := fmt.Sprintf("%s/v1/models", baseURL)
  492. request, err := http.NewRequest("GET", url, nil)
  493. if err != nil {
  494. c.JSON(http.StatusInternalServerError, gin.H{
  495. "success": false,
  496. "message": err.Error(),
  497. })
  498. return
  499. }
  500. request.Header.Set("Authorization", "Bearer "+req.Key)
  501. response, err := client.Do(request)
  502. if err != nil {
  503. c.JSON(http.StatusInternalServerError, gin.H{
  504. "success": false,
  505. "message": err.Error(),
  506. })
  507. return
  508. }
  509. //check status code
  510. if response.StatusCode != http.StatusOK {
  511. c.JSON(http.StatusInternalServerError, gin.H{
  512. "success": false,
  513. "message": "Failed to fetch models",
  514. })
  515. return
  516. }
  517. defer response.Body.Close()
  518. var result struct {
  519. Data []struct {
  520. ID string `json:"id"`
  521. } `json:"data"`
  522. }
  523. if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
  524. c.JSON(http.StatusInternalServerError, gin.H{
  525. "success": false,
  526. "message": err.Error(),
  527. })
  528. return
  529. }
  530. var models []string
  531. for _, model := range result.Data {
  532. models = append(models, model.ID)
  533. }
  534. c.JSON(http.StatusOK, gin.H{
  535. "success": true,
  536. "data": models,
  537. })
  538. }
  539. func BatchSetChannelTag(c *gin.Context) {
  540. channelBatch := ChannelBatch{}
  541. err := c.ShouldBindJSON(&channelBatch)
  542. if err != nil || len(channelBatch.Ids) == 0 {
  543. c.JSON(http.StatusOK, gin.H{
  544. "success": false,
  545. "message": "参数错误",
  546. })
  547. return
  548. }
  549. err = model.BatchSetChannelTag(channelBatch.Ids, channelBatch.Tag)
  550. if err != nil {
  551. c.JSON(http.StatusOK, gin.H{
  552. "success": false,
  553. "message": err.Error(),
  554. })
  555. return
  556. }
  557. c.JSON(http.StatusOK, gin.H{
  558. "success": true,
  559. "message": "",
  560. "data": len(channelBatch.Ids),
  561. })
  562. return
  563. }