modelconfig.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. package model
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "strings"
  7. "time"
  8. "github.com/bytedance/sonic"
  9. "github.com/labring/aiproxy/core/common"
  10. "github.com/labring/aiproxy/core/relay/mode"
  11. "gorm.io/gorm"
  12. )
  13. const (
  14. // /1K tokens
  15. PriceUnit = 1000
  16. )
  17. type ModelConfig struct {
  18. CreatedAt time.Time `gorm:"index;autoCreateTime" json:"created_at"`
  19. UpdatedAt time.Time `gorm:"index;autoUpdateTime" json:"updated_at"`
  20. Config map[ModelConfigKey]any `gorm:"serializer:fastjson;type:text" json:"config,omitempty"`
  21. Plugin map[string]json.RawMessage `gorm:"serializer:fastjson;type:text" json:"plugin,omitempty"`
  22. Model string `gorm:"primaryKey" json:"model"`
  23. Owner ModelOwner `gorm:"type:varchar(255);index" json:"owner"`
  24. Type mode.Mode ` json:"type"`
  25. ExcludeFromTests bool ` json:"exclude_from_tests,omitempty"`
  26. RPM int64 ` json:"rpm,omitempty"`
  27. TPM int64 ` json:"tpm,omitempty"`
  28. // map[size]map[quality]price_per_image
  29. ImageQualityPrices map[string]map[string]float64 `gorm:"serializer:fastjson;type:text" json:"image_quality_prices,omitempty"`
  30. // map[size]price_per_image
  31. ImagePrices map[string]float64 `gorm:"serializer:fastjson;type:text" json:"image_prices,omitempty"`
  32. Price Price `gorm:"embedded" json:"price,omitempty"`
  33. RetryTimes int64 ` json:"retry_times,omitempty"`
  34. Timeout int64 ` json:"timeout,omitempty"`
  35. MaxErrorRate float64 ` json:"max_error_rate,omitempty"`
  36. ForceSaveDetail bool ` json:"force_save_detail,omitempty"`
  37. }
  38. func (c *ModelConfig) BeforeSave(_ *gorm.DB) (err error) {
  39. if c.Model == "" {
  40. return errors.New("model is required")
  41. }
  42. if err := c.Price.ValidateConditionalPrices(); err != nil {
  43. return err
  44. }
  45. return nil
  46. }
  47. func NewDefaultModelConfig(model string) ModelConfig {
  48. return ModelConfig{
  49. Model: model,
  50. }
  51. }
  52. func (c *ModelConfig) LoadPluginConfig(pluginName string, config any) error {
  53. if len(c.Plugin) == 0 {
  54. return nil
  55. }
  56. pluginConfig, ok := c.Plugin[pluginName]
  57. if !ok || len(pluginConfig) == 0 {
  58. return nil
  59. }
  60. return sonic.Unmarshal(pluginConfig, config)
  61. }
  62. func (c *ModelConfig) LoadFromGroupModelConfig(groupModelConfig GroupModelConfig) ModelConfig {
  63. newC := *c
  64. if groupModelConfig.OverrideLimit {
  65. newC.RPM = groupModelConfig.RPM
  66. newC.TPM = groupModelConfig.TPM
  67. }
  68. if groupModelConfig.OverridePrice {
  69. newC.ImagePrices = groupModelConfig.ImagePrices
  70. newC.Price = groupModelConfig.Price
  71. }
  72. if groupModelConfig.OverrideRetryTimes {
  73. newC.RetryTimes = groupModelConfig.RetryTimes
  74. }
  75. if groupModelConfig.OverrideForceSaveDetail {
  76. newC.ForceSaveDetail = groupModelConfig.ForceSaveDetail
  77. }
  78. return newC
  79. }
  80. func (c *ModelConfig) MarshalJSON() ([]byte, error) {
  81. type Alias ModelConfig
  82. a := &struct {
  83. *Alias
  84. CreatedAt int64 `json:"created_at,omitempty"`
  85. UpdatedAt int64 `json:"updated_at,omitempty"`
  86. }{
  87. Alias: (*Alias)(c),
  88. }
  89. if !c.CreatedAt.IsZero() {
  90. a.CreatedAt = c.CreatedAt.UnixMilli()
  91. }
  92. if !c.UpdatedAt.IsZero() {
  93. a.UpdatedAt = c.UpdatedAt.UnixMilli()
  94. }
  95. return sonic.Marshal(a)
  96. }
  97. func (c *ModelConfig) MaxContextTokens() (int, bool) {
  98. return GetModelConfigInt(c.Config, ModelConfigMaxContextTokensKey)
  99. }
  100. func (c *ModelConfig) MaxInputTokens() (int, bool) {
  101. return GetModelConfigInt(c.Config, ModelConfigMaxInputTokensKey)
  102. }
  103. func (c *ModelConfig) MaxOutputTokens() (int, bool) {
  104. return GetModelConfigInt(c.Config, ModelConfigMaxOutputTokensKey)
  105. }
  106. func (c *ModelConfig) SupportVision() (bool, bool) {
  107. return GetModelConfigBool(c.Config, ModelConfigVisionKey)
  108. }
  109. func (c *ModelConfig) SupportVoices() ([]string, bool) {
  110. return GetModelConfigStringSlice(c.Config, ModelConfigSupportVoicesKey)
  111. }
  112. func (c *ModelConfig) SupportToolChoice() (bool, bool) {
  113. return GetModelConfigBool(c.Config, ModelConfigToolChoiceKey)
  114. }
  115. func (c *ModelConfig) SupportFormats() ([]string, bool) {
  116. return GetModelConfigStringSlice(c.Config, ModelConfigSupportFormatsKey)
  117. }
  118. func GetModelConfigs(
  119. page, perPage int,
  120. model string,
  121. ) (configs []*ModelConfig, total int64, err error) {
  122. tx := DB.Model(&ModelConfig{})
  123. if model != "" {
  124. tx = tx.Where("model = ?", model)
  125. }
  126. err = tx.Count(&total).Error
  127. if err != nil {
  128. return nil, 0, err
  129. }
  130. if total <= 0 {
  131. return nil, 0, nil
  132. }
  133. limit, offset := toLimitOffset(page, perPage)
  134. err = tx.
  135. Order("created_at desc").
  136. Omit("created_at", "updated_at").
  137. Limit(limit).
  138. Offset(offset).
  139. Find(&configs).
  140. Error
  141. return configs, total, err
  142. }
  143. func GetAllModelConfigs() (configs []ModelConfig, err error) {
  144. tx := DB.Model(&ModelConfig{})
  145. err = tx.Order("created_at desc").
  146. Omit("created_at", "updated_at").
  147. Find(&configs).
  148. Error
  149. return configs, err
  150. }
  151. func GetModelConfigsByModels(models []string) (configs []ModelConfig, err error) {
  152. tx := DB.Model(&ModelConfig{}).Where("model IN (?)", models)
  153. err = tx.Order("created_at desc").
  154. Omit("created_at", "updated_at").
  155. Find(&configs).
  156. Error
  157. return configs, err
  158. }
  159. func GetModelConfig(model string) (ModelConfig, error) {
  160. config := ModelConfig{}
  161. err := DB.Model(&ModelConfig{}).
  162. Where("model = ?", model).
  163. Omit("created_at", "updated_at").
  164. First(config).
  165. Error
  166. return config, HandleNotFound(err, ErrModelConfigNotFound)
  167. }
  168. func SearchModelConfigs(
  169. keyword string,
  170. page, perPage int,
  171. model string,
  172. owner ModelOwner,
  173. ) (configs []ModelConfig, total int64, err error) {
  174. tx := DB.Model(&ModelConfig{}).Where("model LIKE ?", "%"+keyword+"%")
  175. if model != "" {
  176. tx = tx.Where("model = ?", model)
  177. }
  178. if owner != "" {
  179. tx = tx.Where("owner = ?", owner)
  180. }
  181. if keyword != "" {
  182. var (
  183. conditions []string
  184. values []any
  185. )
  186. if model == "" {
  187. if common.UsingPostgreSQL {
  188. conditions = append(conditions, "model ILIKE ?")
  189. } else {
  190. conditions = append(conditions, "model LIKE ?")
  191. }
  192. values = append(values, "%"+keyword+"%")
  193. }
  194. if owner != "" {
  195. if common.UsingPostgreSQL {
  196. conditions = append(conditions, "owner ILIKE ?")
  197. } else {
  198. conditions = append(conditions, "owner LIKE ?")
  199. }
  200. values = append(values, "%"+string(owner)+"%")
  201. }
  202. if len(conditions) > 0 {
  203. tx = tx.Where(fmt.Sprintf("(%s)", strings.Join(conditions, " OR ")), values...)
  204. }
  205. }
  206. err = tx.Count(&total).Error
  207. if err != nil {
  208. return nil, 0, err
  209. }
  210. if total <= 0 {
  211. return nil, 0, nil
  212. }
  213. limit, offset := toLimitOffset(page, perPage)
  214. err = tx.Order("created_at desc").
  215. Omit("created_at", "updated_at").
  216. Limit(limit).
  217. Offset(offset).
  218. Find(&configs).
  219. Error
  220. return configs, total, err
  221. }
  222. func SaveModelConfig(config ModelConfig) (err error) {
  223. defer func() {
  224. if err == nil {
  225. _ = InitModelConfigAndChannelCache()
  226. }
  227. }()
  228. return DB.Save(&config).Error
  229. }
  230. func SaveModelConfigs(configs []ModelConfig) (err error) {
  231. defer func() {
  232. if err == nil {
  233. _ = InitModelConfigAndChannelCache()
  234. }
  235. }()
  236. return DB.Transaction(func(tx *gorm.DB) error {
  237. for _, config := range configs {
  238. if err := tx.Save(&config).Error; err != nil {
  239. return err
  240. }
  241. }
  242. return nil
  243. })
  244. }
  245. const ErrModelConfigNotFound = "model config"
  246. func DeleteModelConfig(model string) error {
  247. result := DB.Where("model = ?", model).Delete(&ModelConfig{})
  248. return HandleUpdateResult(result, ErrModelConfigNotFound)
  249. }
  250. func DeleteModelConfigsByModels(models []string) error {
  251. return DB.Transaction(func(tx *gorm.DB) error {
  252. return tx.
  253. Where("model IN (?)", models).
  254. Delete(&ModelConfig{}).
  255. Error
  256. })
  257. }