model.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. package controller
  2. import (
  3. "fmt"
  4. "net/http"
  5. "slices"
  6. "sort"
  7. "strconv"
  8. "github.com/bytedance/sonic"
  9. "github.com/gin-gonic/gin"
  10. "github.com/labring/aiproxy/common/config"
  11. "github.com/labring/aiproxy/middleware"
  12. "github.com/labring/aiproxy/model"
  13. "github.com/labring/aiproxy/relay/channeltype"
  14. relaymodel "github.com/labring/aiproxy/relay/model"
  15. log "github.com/sirupsen/logrus"
  16. )
  17. // https://platform.openai.com/docs/api-reference/models/list
  18. type OpenAIModelPermission struct {
  19. Group *string `json:"group"`
  20. ID string `json:"id"`
  21. Object string `json:"object"`
  22. Organization string `json:"organization"`
  23. Created int `json:"created"`
  24. AllowCreateEngine bool `json:"allow_create_engine"`
  25. AllowSampling bool `json:"allow_sampling"`
  26. AllowLogprobs bool `json:"allow_logprobs"`
  27. AllowSearchIndices bool `json:"allow_search_indices"`
  28. AllowView bool `json:"allow_view"`
  29. AllowFineTuning bool `json:"allow_fine_tuning"`
  30. IsBlocking bool `json:"is_blocking"`
  31. }
  32. type OpenAIModels struct {
  33. Parent *string `json:"parent"`
  34. ID string `json:"id"`
  35. Object string `json:"object"`
  36. OwnedBy string `json:"owned_by"`
  37. Root string `json:"root"`
  38. Permission []OpenAIModelPermission `json:"permission"`
  39. Created int `json:"created"`
  40. }
  41. type BuiltinModelConfig model.ModelConfig
  42. func (c *BuiltinModelConfig) MarshalJSON() ([]byte, error) {
  43. type Alias BuiltinModelConfig
  44. return sonic.Marshal(&struct {
  45. *Alias
  46. CreatedAt int64 `json:"created_at,omitempty"`
  47. UpdatedAt int64 `json:"updated_at,omitempty"`
  48. }{
  49. Alias: (*Alias)(c),
  50. })
  51. }
  52. func SortBuiltinModelConfigsFunc(i, j *BuiltinModelConfig) int {
  53. return model.SortModelConfigsFunc((*model.ModelConfig)(i), (*model.ModelConfig)(j))
  54. }
  55. var (
  56. builtinModels []*BuiltinModelConfig
  57. builtinModelsMap map[string]*OpenAIModels
  58. builtinChannelID2Models map[int][]*BuiltinModelConfig
  59. )
  60. var permission = []OpenAIModelPermission{
  61. {
  62. ID: "modelperm-LwHkVFn8AcMItP432fKKDIKJ",
  63. Object: "model_permission",
  64. Created: 1626777600,
  65. AllowCreateEngine: true,
  66. AllowSampling: true,
  67. AllowLogprobs: true,
  68. AllowSearchIndices: false,
  69. AllowView: true,
  70. AllowFineTuning: false,
  71. Organization: "*",
  72. Group: nil,
  73. IsBlocking: false,
  74. },
  75. }
  76. func init() {
  77. builtinChannelID2Models = make(map[int][]*BuiltinModelConfig)
  78. builtinModelsMap = make(map[string]*OpenAIModels)
  79. // https://platform.openai.com/docs/models/model-endpoint-compatibility
  80. for i, adaptor := range channeltype.ChannelAdaptor {
  81. modelNames := adaptor.GetModelList()
  82. builtinChannelID2Models[i] = make([]*BuiltinModelConfig, len(modelNames))
  83. for idx, _model := range modelNames {
  84. if _model.Owner == "" {
  85. _model.Owner = model.ModelOwner(adaptor.GetChannelName())
  86. }
  87. if v, ok := builtinModelsMap[_model.Model]; !ok {
  88. builtinModelsMap[_model.Model] = &OpenAIModels{
  89. ID: _model.Model,
  90. Object: "model",
  91. Created: 1626777600,
  92. OwnedBy: string(_model.Owner),
  93. Permission: permission,
  94. Root: _model.Model,
  95. Parent: nil,
  96. }
  97. builtinModels = append(builtinModels, (*BuiltinModelConfig)(_model))
  98. } else if v.OwnedBy != string(_model.Owner) {
  99. log.Fatalf("model %s owner mismatch, expect %s, actual %s", _model.Model, string(_model.Owner), v.OwnedBy)
  100. }
  101. builtinChannelID2Models[i][idx] = (*BuiltinModelConfig)(_model)
  102. }
  103. }
  104. for _, models := range builtinChannelID2Models {
  105. sort.Slice(models, func(i, j int) bool {
  106. return models[i].Model < models[j].Model
  107. })
  108. slices.SortStableFunc(models, SortBuiltinModelConfigsFunc)
  109. }
  110. slices.SortStableFunc(builtinModels, SortBuiltinModelConfigsFunc)
  111. }
  112. func BuiltinModels(c *gin.Context) {
  113. middleware.SuccessResponse(c, builtinModels)
  114. }
  115. func ChannelBuiltinModels(c *gin.Context) {
  116. middleware.SuccessResponse(c, builtinChannelID2Models)
  117. }
  118. func ChannelBuiltinModelsByType(c *gin.Context) {
  119. channelType := c.Param("type")
  120. if channelType == "" {
  121. middleware.ErrorResponse(c, http.StatusOK, "type is required")
  122. return
  123. }
  124. channelTypeInt, err := strconv.Atoi(channelType)
  125. if err != nil {
  126. middleware.ErrorResponse(c, http.StatusOK, "invalid type")
  127. return
  128. }
  129. middleware.SuccessResponse(c, builtinChannelID2Models[channelTypeInt])
  130. }
  131. func ChannelDefaultModelsAndMapping(c *gin.Context) {
  132. middleware.SuccessResponse(c, gin.H{
  133. "models": config.GetDefaultChannelModels(),
  134. "mapping": config.GetDefaultChannelModelMapping(),
  135. })
  136. }
  137. func ChannelDefaultModelsAndMappingByType(c *gin.Context) {
  138. channelType := c.Param("type")
  139. if channelType == "" {
  140. middleware.ErrorResponse(c, http.StatusOK, "type is required")
  141. return
  142. }
  143. channelTypeInt, err := strconv.Atoi(channelType)
  144. if err != nil {
  145. middleware.ErrorResponse(c, http.StatusOK, "invalid type")
  146. return
  147. }
  148. middleware.SuccessResponse(c, gin.H{
  149. "models": config.GetDefaultChannelModels()[channelTypeInt],
  150. "mapping": config.GetDefaultChannelModelMapping()[channelTypeInt],
  151. })
  152. }
  153. func EnabledModels(c *gin.Context) {
  154. middleware.SuccessResponse(c, model.LoadModelCaches().EnabledModelConfigs)
  155. }
  156. func ChannelEnabledModels(c *gin.Context) {
  157. middleware.SuccessResponse(c, model.LoadModelCaches().EnabledChannelType2ModelConfigs)
  158. }
  159. func ChannelEnabledModelsByType(c *gin.Context) {
  160. channelTypeStr := c.Param("type")
  161. if channelTypeStr == "" {
  162. middleware.ErrorResponse(c, http.StatusOK, "type is required")
  163. return
  164. }
  165. channelTypeInt, err := strconv.Atoi(channelTypeStr)
  166. if err != nil {
  167. middleware.ErrorResponse(c, http.StatusOK, "invalid type")
  168. return
  169. }
  170. middleware.SuccessResponse(c, model.LoadModelCaches().EnabledChannelType2ModelConfigs[channelTypeInt])
  171. }
  172. func ListModels(c *gin.Context) {
  173. enabledModelConfigsMap := middleware.GetModelCaches(c).EnabledModelConfigsMap
  174. token := middleware.GetToken(c)
  175. availableOpenAIModels := make([]*OpenAIModels, 0, len(token.Models))
  176. for _, model := range token.Models {
  177. if mc, ok := enabledModelConfigsMap[model]; ok {
  178. availableOpenAIModels = append(availableOpenAIModels, &OpenAIModels{
  179. ID: model,
  180. Object: "model",
  181. Created: 1626777600,
  182. OwnedBy: string(mc.Owner),
  183. Root: model,
  184. Permission: permission,
  185. Parent: nil,
  186. })
  187. }
  188. }
  189. c.JSON(http.StatusOK, gin.H{
  190. "object": "list",
  191. "data": availableOpenAIModels,
  192. })
  193. }
  194. func RetrieveModel(c *gin.Context) {
  195. modelName := c.Param("model")
  196. enabledModelConfigsMap := middleware.GetModelCaches(c).EnabledModelConfigsMap
  197. mc, ok := enabledModelConfigsMap[modelName]
  198. if ok {
  199. token := middleware.GetToken(c)
  200. ok = slices.Contains(token.Models, modelName)
  201. }
  202. if !ok {
  203. c.JSON(200, gin.H{
  204. "error": &relaymodel.Error{
  205. Message: fmt.Sprintf("the model '%s' does not exist", modelName),
  206. Type: "invalid_request_error",
  207. Param: "model",
  208. Code: "model_not_found",
  209. },
  210. })
  211. return
  212. }
  213. c.JSON(200, &OpenAIModels{
  214. ID: modelName,
  215. Object: "model",
  216. Created: 1626777600,
  217. OwnedBy: string(mc.Owner),
  218. Root: modelName,
  219. Permission: permission,
  220. Parent: nil,
  221. })
  222. }