channel.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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. channel.BaseURL = &baseURL
  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. }
  402. func DeleteChannelBatch(c *gin.Context) {
  403. channelBatch := ChannelBatch{}
  404. err := c.ShouldBindJSON(&channelBatch)
  405. if err != nil || len(channelBatch.Ids) == 0 {
  406. c.JSON(http.StatusOK, gin.H{
  407. "success": false,
  408. "message": "参数错误",
  409. })
  410. return
  411. }
  412. err = model.BatchDeleteChannels(channelBatch.Ids)
  413. if err != nil {
  414. c.JSON(http.StatusOK, gin.H{
  415. "success": false,
  416. "message": err.Error(),
  417. })
  418. return
  419. }
  420. c.JSON(http.StatusOK, gin.H{
  421. "success": true,
  422. "message": "",
  423. "data": len(channelBatch.Ids),
  424. })
  425. return
  426. }
  427. func UpdateChannel(c *gin.Context) {
  428. channel := model.Channel{}
  429. err := c.ShouldBindJSON(&channel)
  430. if err != nil {
  431. c.JSON(http.StatusOK, gin.H{
  432. "success": false,
  433. "message": err.Error(),
  434. })
  435. return
  436. }
  437. if channel.Type == common.ChannelTypeVertexAi {
  438. if channel.Other == "" {
  439. c.JSON(http.StatusOK, gin.H{
  440. "success": false,
  441. "message": "部署地区不能为空",
  442. })
  443. return
  444. } else {
  445. if common.IsJsonStr(channel.Other) {
  446. // must have default
  447. regionMap := common.StrToMap(channel.Other)
  448. if regionMap["default"] == nil {
  449. c.JSON(http.StatusOK, gin.H{
  450. "success": false,
  451. "message": "部署地区必须包含default字段",
  452. })
  453. return
  454. }
  455. }
  456. }
  457. }
  458. err = channel.Update()
  459. if err != nil {
  460. c.JSON(http.StatusOK, gin.H{
  461. "success": false,
  462. "message": err.Error(),
  463. })
  464. return
  465. }
  466. c.JSON(http.StatusOK, gin.H{
  467. "success": true,
  468. "message": "",
  469. "data": channel,
  470. })
  471. return
  472. }
  473. func FetchModels(c *gin.Context) {
  474. var req struct {
  475. BaseURL string `json:"base_url"`
  476. Key string `json:"key"`
  477. }
  478. if err := c.ShouldBindJSON(&req); err != nil {
  479. c.JSON(http.StatusBadRequest, gin.H{
  480. "success": false,
  481. "message": "Invalid request",
  482. })
  483. return
  484. }
  485. baseURL := req.BaseURL
  486. if baseURL == "" {
  487. baseURL = "https://api.openai.com"
  488. }
  489. client := &http.Client{}
  490. url := fmt.Sprintf("%s/v1/models", baseURL)
  491. request, err := http.NewRequest("GET", url, nil)
  492. if err != nil {
  493. c.JSON(http.StatusInternalServerError, gin.H{
  494. "success": false,
  495. "message": err.Error(),
  496. })
  497. return
  498. }
  499. request.Header.Set("Authorization", "Bearer "+req.Key)
  500. response, err := client.Do(request)
  501. if err != nil {
  502. c.JSON(http.StatusInternalServerError, gin.H{
  503. "success": false,
  504. "message": err.Error(),
  505. })
  506. return
  507. }
  508. //check status code
  509. if response.StatusCode != http.StatusOK {
  510. c.JSON(http.StatusInternalServerError, gin.H{
  511. "success": false,
  512. "message": "Failed to fetch models",
  513. })
  514. return
  515. }
  516. defer response.Body.Close()
  517. var result struct {
  518. Data []struct {
  519. ID string `json:"id"`
  520. } `json:"data"`
  521. }
  522. if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
  523. c.JSON(http.StatusInternalServerError, gin.H{
  524. "success": false,
  525. "message": err.Error(),
  526. })
  527. return
  528. }
  529. var models []string
  530. for _, model := range result.Data {
  531. models = append(models, model.ID)
  532. }
  533. c.JSON(http.StatusOK, gin.H{
  534. "success": true,
  535. "data": models,
  536. })
  537. }