channel.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  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. // Validate the length of the model name
  263. models := strings.Split(localChannel.Models, ",")
  264. for _, model := range models {
  265. if len(model) > 255 {
  266. c.JSON(http.StatusOK, gin.H{
  267. "success": false,
  268. "message": fmt.Sprintf("模型名称过长: %s", model),
  269. })
  270. return
  271. }
  272. }
  273. channels = append(channels, localChannel)
  274. }
  275. err = model.BatchInsertChannels(channels)
  276. if err != nil {
  277. c.JSON(http.StatusOK, gin.H{
  278. "success": false,
  279. "message": err.Error(),
  280. })
  281. return
  282. }
  283. c.JSON(http.StatusOK, gin.H{
  284. "success": true,
  285. "message": "",
  286. })
  287. return
  288. }
  289. func DeleteChannel(c *gin.Context) {
  290. id, _ := strconv.Atoi(c.Param("id"))
  291. channel := model.Channel{Id: id}
  292. err := channel.Delete()
  293. if err != nil {
  294. c.JSON(http.StatusOK, gin.H{
  295. "success": false,
  296. "message": err.Error(),
  297. })
  298. return
  299. }
  300. c.JSON(http.StatusOK, gin.H{
  301. "success": true,
  302. "message": "",
  303. })
  304. return
  305. }
  306. func DeleteDisabledChannel(c *gin.Context) {
  307. rows, err := model.DeleteDisabledChannel()
  308. if err != nil {
  309. c.JSON(http.StatusOK, gin.H{
  310. "success": false,
  311. "message": err.Error(),
  312. })
  313. return
  314. }
  315. c.JSON(http.StatusOK, gin.H{
  316. "success": true,
  317. "message": "",
  318. "data": rows,
  319. })
  320. return
  321. }
  322. type ChannelTag struct {
  323. Tag string `json:"tag"`
  324. NewTag *string `json:"new_tag"`
  325. Priority *int64 `json:"priority"`
  326. Weight *uint `json:"weight"`
  327. ModelMapping *string `json:"model_mapping"`
  328. Models *string `json:"models"`
  329. Groups *string `json:"groups"`
  330. }
  331. func DisableTagChannels(c *gin.Context) {
  332. channelTag := ChannelTag{}
  333. err := c.ShouldBindJSON(&channelTag)
  334. if err != nil || channelTag.Tag == "" {
  335. c.JSON(http.StatusOK, gin.H{
  336. "success": false,
  337. "message": "参数错误",
  338. })
  339. return
  340. }
  341. err = model.DisableChannelByTag(channelTag.Tag)
  342. if err != nil {
  343. c.JSON(http.StatusOK, gin.H{
  344. "success": false,
  345. "message": err.Error(),
  346. })
  347. return
  348. }
  349. c.JSON(http.StatusOK, gin.H{
  350. "success": true,
  351. "message": "",
  352. })
  353. return
  354. }
  355. func EnableTagChannels(c *gin.Context) {
  356. channelTag := ChannelTag{}
  357. err := c.ShouldBindJSON(&channelTag)
  358. if err != nil || channelTag.Tag == "" {
  359. c.JSON(http.StatusOK, gin.H{
  360. "success": false,
  361. "message": "参数错误",
  362. })
  363. return
  364. }
  365. err = model.EnableChannelByTag(channelTag.Tag)
  366. if err != nil {
  367. c.JSON(http.StatusOK, gin.H{
  368. "success": false,
  369. "message": err.Error(),
  370. })
  371. return
  372. }
  373. c.JSON(http.StatusOK, gin.H{
  374. "success": true,
  375. "message": "",
  376. })
  377. return
  378. }
  379. func EditTagChannels(c *gin.Context) {
  380. channelTag := ChannelTag{}
  381. err := c.ShouldBindJSON(&channelTag)
  382. if err != nil {
  383. c.JSON(http.StatusOK, gin.H{
  384. "success": false,
  385. "message": "参数错误",
  386. })
  387. return
  388. }
  389. if channelTag.Tag == "" {
  390. c.JSON(http.StatusOK, gin.H{
  391. "success": false,
  392. "message": "tag不能为空",
  393. })
  394. return
  395. }
  396. err = model.EditChannelByTag(channelTag.Tag, channelTag.NewTag, channelTag.ModelMapping, channelTag.Models, channelTag.Groups, channelTag.Priority, channelTag.Weight)
  397. if err != nil {
  398. c.JSON(http.StatusOK, gin.H{
  399. "success": false,
  400. "message": err.Error(),
  401. })
  402. return
  403. }
  404. c.JSON(http.StatusOK, gin.H{
  405. "success": true,
  406. "message": "",
  407. })
  408. return
  409. }
  410. type ChannelBatch struct {
  411. Ids []int `json:"ids"`
  412. Tag *string `json:"tag"`
  413. }
  414. func DeleteChannelBatch(c *gin.Context) {
  415. channelBatch := ChannelBatch{}
  416. err := c.ShouldBindJSON(&channelBatch)
  417. if err != nil || len(channelBatch.Ids) == 0 {
  418. c.JSON(http.StatusOK, gin.H{
  419. "success": false,
  420. "message": "参数错误",
  421. })
  422. return
  423. }
  424. err = model.BatchDeleteChannels(channelBatch.Ids)
  425. if err != nil {
  426. c.JSON(http.StatusOK, gin.H{
  427. "success": false,
  428. "message": err.Error(),
  429. })
  430. return
  431. }
  432. c.JSON(http.StatusOK, gin.H{
  433. "success": true,
  434. "message": "",
  435. "data": len(channelBatch.Ids),
  436. })
  437. return
  438. }
  439. func UpdateChannel(c *gin.Context) {
  440. channel := model.Channel{}
  441. err := c.ShouldBindJSON(&channel)
  442. if err != nil {
  443. c.JSON(http.StatusOK, gin.H{
  444. "success": false,
  445. "message": err.Error(),
  446. })
  447. return
  448. }
  449. if channel.Type == common.ChannelTypeVertexAi {
  450. if channel.Other == "" {
  451. c.JSON(http.StatusOK, gin.H{
  452. "success": false,
  453. "message": "部署地区不能为空",
  454. })
  455. return
  456. } else {
  457. if common.IsJsonStr(channel.Other) {
  458. // must have default
  459. regionMap := common.StrToMap(channel.Other)
  460. if regionMap["default"] == nil {
  461. c.JSON(http.StatusOK, gin.H{
  462. "success": false,
  463. "message": "部署地区必须包含default字段",
  464. })
  465. return
  466. }
  467. }
  468. }
  469. }
  470. err = channel.Update()
  471. if err != nil {
  472. c.JSON(http.StatusOK, gin.H{
  473. "success": false,
  474. "message": err.Error(),
  475. })
  476. return
  477. }
  478. c.JSON(http.StatusOK, gin.H{
  479. "success": true,
  480. "message": "",
  481. "data": channel,
  482. })
  483. return
  484. }
  485. func FetchModels(c *gin.Context) {
  486. var req struct {
  487. BaseURL string `json:"base_url"`
  488. Key string `json:"key"`
  489. }
  490. if err := c.ShouldBindJSON(&req); err != nil {
  491. c.JSON(http.StatusBadRequest, gin.H{
  492. "success": false,
  493. "message": "Invalid request",
  494. })
  495. return
  496. }
  497. baseURL := req.BaseURL
  498. if baseURL == "" {
  499. baseURL = "https://api.openai.com"
  500. }
  501. client := &http.Client{}
  502. url := fmt.Sprintf("%s/v1/models", baseURL)
  503. request, err := http.NewRequest("GET", url, nil)
  504. if err != nil {
  505. c.JSON(http.StatusInternalServerError, gin.H{
  506. "success": false,
  507. "message": err.Error(),
  508. })
  509. return
  510. }
  511. request.Header.Set("Authorization", "Bearer "+req.Key)
  512. response, err := client.Do(request)
  513. if err != nil {
  514. c.JSON(http.StatusInternalServerError, gin.H{
  515. "success": false,
  516. "message": err.Error(),
  517. })
  518. return
  519. }
  520. //check status code
  521. if response.StatusCode != http.StatusOK {
  522. c.JSON(http.StatusInternalServerError, gin.H{
  523. "success": false,
  524. "message": "Failed to fetch models",
  525. })
  526. return
  527. }
  528. defer response.Body.Close()
  529. var result struct {
  530. Data []struct {
  531. ID string `json:"id"`
  532. } `json:"data"`
  533. }
  534. if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
  535. c.JSON(http.StatusInternalServerError, gin.H{
  536. "success": false,
  537. "message": err.Error(),
  538. })
  539. return
  540. }
  541. var models []string
  542. for _, model := range result.Data {
  543. models = append(models, model.ID)
  544. }
  545. c.JSON(http.StatusOK, gin.H{
  546. "success": true,
  547. "data": models,
  548. })
  549. }
  550. func BatchSetChannelTag(c *gin.Context) {
  551. channelBatch := ChannelBatch{}
  552. err := c.ShouldBindJSON(&channelBatch)
  553. if err != nil || len(channelBatch.Ids) == 0 {
  554. c.JSON(http.StatusOK, gin.H{
  555. "success": false,
  556. "message": "参数错误",
  557. })
  558. return
  559. }
  560. err = model.BatchSetChannelTag(channelBatch.Ids, channelBatch.Tag)
  561. if err != nil {
  562. c.JSON(http.StatusOK, gin.H{
  563. "success": false,
  564. "message": err.Error(),
  565. })
  566. return
  567. }
  568. c.JSON(http.StatusOK, gin.H{
  569. "success": true,
  570. "message": "",
  571. "data": len(channelBatch.Ids),
  572. })
  573. return
  574. }