modelconfig.go 8.5 KB

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