model

package
v0.0.0-...-c78ba3f Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 16, 2026 License: MIT Imports: 53 Imported by: 75

Documentation

Index

Constants

View Source
const (
	AsyncUsageDefaultPollDelay = 3 * time.Second
	AsyncUsageMaxPollDelay     = 3 * time.Minute
)
View Source
const (
	SyncFrequency    = time.Minute * 3
	GroupModelTPMKey = "group:%s:model_tpm"
)
View Source
const (
	ChannelStatusUnknown  = 0
	ChannelStatusEnabled  = 1
	ChannelStatusDisabled = 2
)
View Source
const (
	DefaultPriority = 10
	MaxPriority     = 1000000
)
View Source
const (
	GroupStatusEnabled  = 1
	GroupStatusDisabled = 2
	GroupStatusInternal = 3
)
View Source
const (
	ErrPublicMCPNotFound       = "public mcp"
	ErrMCPReusingParamNotFound = "mcp reusing param"
)
View Source
const (
	StorePrefixResponse        = "response"
	StorePrefixVideoJob        = "video_job"
	StorePrefixVideoGeneration = "video_generation"
	StorePrefixGeminiFile      = "gemini_file"
	StorePrefixPromptCacheKey  = "prompt_cache_key"
	StorePrefixCacheFollow     = "cachefollow"
	StorePrefixCacheFollowUser = "cachefollow_user"
)
View Source
const (
	StoreCacheKey         = "storev2:%s:%d:%s:%s"
	StoreCacheNotFoundKey = "storev2notfound:%s:%d:%s:%s"
)
View Source
const (
	PeriodTypeDaily   = "daily"
	PeriodTypeWeekly  = "weekly"
	PeriodTypeMonthly = "monthly"
)
View Source
const (
	TokenStatusEnabled  = 1
	TokenStatusDisabled = 2
)
View Source
const (
	ChannelDefaultSet = "default"
)
View Source
const ClaudeLongContextInputTokensThreshold = int64(200000)
View Source
const (
	ErrChannelNotFound = "channel"
)
View Source
const ErrGroupChannelNotFound = "group_channel"
View Source
const (
	ErrGroupMCPNotFound = "group mcp"
)
View Source
const (
	ErrGroupNotFound = "group"
)
View Source
const ErrGroupScopeModelConfigNotFound = "group_scope_model_config"
View Source
const ErrModelConfigNotFound = "model config"
View Source
const (
	ErrStoreNotFound = "store id"
)
View Source
const (
	ErrTokenNotFound = "token"
)
View Source
const (
	GroupCacheKey = "group:%s"
)
View Source
const GroupChannelsCacheKey = "group_channels:%s"
View Source
const (
	GroupMCPCacheKey = "group_mcp:%s:%s"
)
View Source
const (
	GroupModelConfigCacheKey = "group_model_config"
)
View Source
const GroupScopeModelConfigsCacheKey = "group_scope_model_configs:%s"
View Source
const (
	// /1K tokens
	PriceUnit = 1000
)
View Source
const (
	PublicMCPCacheKey = "public_mcp:%s"
)
View Source
const (
	PublicMCPReusingParamCacheKey = "public_mcp_param:%s:%s"
)
View Source
const (
	TokenCacheKey = "token:%s"
)

Variables

View Source
var (
	DB    *gorm.DB
	LogDB *gorm.DB
)
View Source
var ErrUnknownOptionKey = errors.New("unknown option key")

Functions

func AsyncUsageBackoffDelay

func AsyncUsageBackoffDelay(
	retryCount int,
) time.Duration

func BatchInsertChannels

func BatchInsertChannels(channels []*Channel) (err error)

func BatchInsertGroupChannels

func BatchInsertGroupChannels(channels []*GroupChannel) (err error)

func BatchRecordLogs

func BatchRecordLogs(
	now time.Time,
	requestID string,
	requestAt time.Time,
	retryAt time.Time,
	firstByteAt time.Time,
	group string,
	code int,
	channelScope ChannelScope,
	channelID int,
	modelName string,
	tokenID int,
	tokenName string,
	endpoint string,
	content string,
	mode int,
	ip string,
	retryTimes int,
	requestDetail *RequestDetail,
	downstreamResult bool,
	usage Usage,
	usageContext UsageContext,
	modelPrice Price,
	amount Amount,
	user string,
	metadata map[string]string,
	promptCacheKey string,
	upstreamID string,
	asyncUsageStatus AsyncUsageStatus,
	summaryServiceTier string,
	summaryClaudeLongContext bool,
) (err error)

func BatchUpdateSummary

func BatchUpdateSummary(
	now time.Time,
	requestAt time.Time,
	firstByteAt time.Time,
	group string,
	code int,
	channelScope ChannelScope,
	channelID int,
	modelName string,
	tokenID int,
	tokenName string,
	downstreamResult bool,
	usage Usage,
	amount Amount,
	serviceTier string,
	summaryClaudeLongContext bool,
)

func BatchUpdateSummaryOnlyUsage

func BatchUpdateSummaryOnlyUsage(
	now time.Time,
	requestAt time.Time,
	group string,
	channelScope ChannelScope,
	channelID int,
	modelName string,
	tokenID int,
	tokenName string,
	usage Usage,
	amount Amount,
	serviceTier string,
	summaryClaudeLongContext bool,
)

func CacheDeleteGroup

func CacheDeleteGroup(id string) error

func CacheDeleteGroupChannels

func CacheDeleteGroupChannels(group string) error

func CacheDeleteGroupMCP

func CacheDeleteGroupMCP(groupID, mcpID string) error

func CacheDeleteGroupScopeModelConfig

func CacheDeleteGroupScopeModelConfig(group string) error

func CacheDeletePublicMCP

func CacheDeletePublicMCP(mcpID string) error

func CacheDeletePublicMCPReusingParam

func CacheDeletePublicMCPReusingParam(mcpID, groupID string) error

func CacheDeleteToken

func CacheDeleteToken(key string) error

func CacheFollowStoreID

func CacheFollowStoreID(modelName string, keyType CacheKeyType) string

func CacheFollowUserStoreID

func CacheFollowUserStoreID(modelName, user string, keyType CacheKeyType) string

func CacheResetTokenPeriodUsage

func CacheResetTokenPeriodUsage(
	key string,
	periodLastUpdateTime time.Time,
	periodLastUpdateAmount float64,
) error

func CacheSetGroup

func CacheSetGroup(group *GroupCache) error

func CacheSetGroupChannels

func CacheSetGroupChannels(cache *GroupChannelsCache) error

func CacheSetGroupMCP

func CacheSetGroupMCP(groupMCP *GroupMCPCache) error

func CacheSetGroupScopeModelConfigs

func CacheSetGroupScopeModelConfigs(cache *GroupScopeModelConfigsCache) error

func CacheSetPublicMCP

func CacheSetPublicMCP(publicMCP *PublicMCPCache) error

func CacheSetPublicMCPReusingParam

func CacheSetPublicMCPReusingParam(param PublicMCPReusingParamCache) error

func CacheSetStore

func CacheSetStore(store *StoreCache) error

func CacheSetStoreByScope

func CacheSetStoreByScope(store *StoreCache, scope ChannelScope) error

func CacheSetToken

func CacheSetToken(token *TokenCache) error

func CacheUpdateGroupMCPStatus

func CacheUpdateGroupMCPStatus(groupID, mcpID string, status GroupMCPStatus) error

func CacheUpdateGroupRPMRatio

func CacheUpdateGroupRPMRatio(id string, rpmRatio float64) error

func CacheUpdateGroupStatus

func CacheUpdateGroupStatus(id string, status int) error

func CacheUpdateGroupTPMRatio

func CacheUpdateGroupTPMRatio(id string, tpmRatio float64) error

func CacheUpdateGroupUsedAmountOnlyIncrease

func CacheUpdateGroupUsedAmountOnlyIncrease(id string, amount float64) error

func CacheUpdatePublicMCPStatus

func CacheUpdatePublicMCPStatus(mcpID string, status PublicMCPStatus) error

func CacheUpdateTokenName

func CacheUpdateTokenName(key, name string) error

func CacheUpdateTokenStatus

func CacheUpdateTokenStatus(key string, status int) error

func CacheUpdateTokenUsedAmountOnlyIncrease

func CacheUpdateTokenUsedAmountOnlyIncrease(key string, amount float64) error

func ChannelAccessModels

func ChannelAccessModels(channel *Channel) []string

func ChannelSupportsModel

func ChannelSupportsModel(channel *Channel, modelName string) bool

func ChannelTypeNameToType

func ChannelTypeNameToType(typeName string) int

ChannelTypeNameToType converts a channel type name to its numeric type

func CheckModelConfigExist

func CheckModelConfigExist(models []string) error

func ClaimedAsyncUsageInfoExists

func ClaimedAsyncUsageInfoExists(info *AsyncUsageInfo) (bool, error)

func CleanBatchUpdatesSummary

func CleanBatchUpdatesSummary(ctx context.Context)

func CleanLog

func CleanLog(batchSize int, optimize bool) (err error)

func CleanupFinishedAsyncUsages

func CleanupFinishedAsyncUsages(olderThan time.Duration, batchSize int) error

func ClearGroupChannelLastTestErrorAt

func ClearGroupChannelLastTestErrorAt(group string, id int) error

func ClearLastTestErrorAt

func ClearLastTestErrorAt(id int) error

func CloseDB

func CloseDB() error

func CompleteClaimedAsyncUsageInfo

func CompleteClaimedAsyncUsageInfo(info *AsyncUsageInfo) (bool, error)

func CreateAsyncUsageInfo

func CreateAsyncUsageInfo(info *AsyncUsageInfo) error

func CreateConsumeError

func CreateConsumeError(
	requestID string,
	requestAt time.Time,
	group, tokenName, model, content string,
	usedAmount float64,
	tokenID int,
) error

func CreateGroup

func CreateGroup(group *Group) error

func CreateGroupChannelLogIndexes

func CreateGroupChannelLogIndexes(db *gorm.DB) error

func CreateGroupChannelSummaryIndexs

func CreateGroupChannelSummaryIndexs(db *gorm.DB) error

func CreateGroupChannelSummaryMinuteIndexs

func CreateGroupChannelSummaryMinuteIndexs(db *gorm.DB) error

func CreateGroupChannelTokenSummaryIndexs

func CreateGroupChannelTokenSummaryIndexs(db *gorm.DB) error

func CreateGroupChannelTokenSummaryMinuteIndexs

func CreateGroupChannelTokenSummaryMinuteIndexs(db *gorm.DB) error

func CreateGroupMCP

func CreateGroupMCP(mcp *GroupMCP) error

CreateGroupMCP creates a new GroupMCP

func CreateGroupSummaryIndexs

func CreateGroupSummaryIndexs(db *gorm.DB) error

func CreateGroupSummaryMinuteIndexs

func CreateGroupSummaryMinuteIndexs(db *gorm.DB) error

func CreateLogIndexes

func CreateLogIndexes(db *gorm.DB) error

func CreatePublicMCP

func CreatePublicMCP(mcp *PublicMCP) error

CreatePublicMCP creates a new MCP

func CreateSummaryIndexs

func CreateSummaryIndexs(db *gorm.DB) error

func CreateSummaryMinuteIndexs

func CreateSummaryMinuteIndexs(db *gorm.DB) error

func DeleteChannelByID

func DeleteChannelByID(id int) (err error)

func DeleteChannelsByIDs

func DeleteChannelsByIDs(ids []int) (err error)

func DeleteGlobalGroupChannelByID

func DeleteGlobalGroupChannelByID(id int) error

func DeleteGlobalGroupChannelsByIDs

func DeleteGlobalGroupChannelsByIDs(ids []int) (err error)

func DeleteGroupByID

func DeleteGroupByID(id string) (err error)

func DeleteGroupChannelByID

func DeleteGroupChannelByID(group string, id int) (err error)

func DeleteGroupChannelLogs

func DeleteGroupChannelLogs(groupID string) (int64, error)

func DeleteGroupChannelsByIDs

func DeleteGroupChannelsByIDs(group string, ids []int) (err error)

func DeleteGroupLogs

func DeleteGroupLogs(groupID string) (int64, error)

func DeleteGroupMCP

func DeleteGroupMCP(id, groupID string) (err error)

DeleteGroupMCP deletes a GroupMCP by ID and GroupID

func DeleteGroupModelConfig

func DeleteGroupModelConfig(groupID, model string) error

func DeleteGroupModelConfigs

func DeleteGroupModelConfigs(groupID string, models []string) error

func DeleteGroupScopeModelConfig

func DeleteGroupScopeModelConfig(group, modelName string) error

func DeleteGroupScopeModelConfigsByModels

func DeleteGroupScopeModelConfigsByModels(group string, models []string) error

func DeleteGroupTokenByID

func DeleteGroupTokenByID(groupID string, id int) (err error)

func DeleteGroupTokensByIDs

func DeleteGroupTokensByIDs(group string, ids []int) (err error)

func DeleteGroupsByIDs

func DeleteGroupsByIDs(ids []string) (err error)

func DeleteModelConfig

func DeleteModelConfig(model string) error

func DeleteModelConfigsByModels

func DeleteModelConfigsByModels(models []string) error

func DeleteOldGroupChannelLog

func DeleteOldGroupChannelLog(timestamp time.Time) (int64, error)

func DeleteOldGroupChannelLogForGroup

func DeleteOldGroupChannelLogForGroup(groupID string, timestamp time.Time) (int64, error)

func DeleteOldLog

func DeleteOldLog(timestamp time.Time) (int64, error)

func DeletePublicMCP

func DeletePublicMCP(id string) (err error)

DeletePublicMCP deletes an MCP by ID

func DeletePublicMCPReusingParam

func DeletePublicMCPReusingParam(mcpID, groupID string) (err error)

DeletePublicMCPReusingParam deletes a GroupMCPReusingParam

func DeleteTokenByID

func DeleteTokenByID(id int) (err error)

func DeleteTokensByIDs

func DeleteTokensByIDs(ids []int) (err error)

func FailClaimedAsyncUsageInfo

func FailClaimedAsyncUsageInfo(info *AsyncUsageInfo) (bool, error)

func FilterModelsBySet

func FilterModelsBySet(
	modelsBySet map[string][]string,
	availableSets []string,
) map[string][]string

func FindModelWithAllowList

func FindModelWithAllowList(
	allowedModels []string,
	modelName string,
	availableSets []string,
	modelsBySet map[string][]string,
) string

func FindTokenModel

func FindTokenModel(
	token TokenCache,
	modelName string,
	availableSets []string,
	modelsBySet map[string][]string,
) string

func GeminiFileStoreID

func GeminiFileStoreID(fileID string) string

func GetChannelLastRequestTimeMinute

func GetChannelLastRequestTimeMinute(channelID int) (time.Time, error)

func GetGlobalGroupChannelTokenUsedModels

func GetGlobalGroupChannelTokenUsedModels(
	group, tokenName string,
	start, end time.Time,
) ([]string, error)

func GetGlobalGroupChannelTokenUsedModelsMinute

func GetGlobalGroupChannelTokenUsedModelsMinute(
	group, tokenName string,
	start, end time.Time,
) ([]string, error)

func GetGlobalGroupChannelTokenUsedTokenNames

func GetGlobalGroupChannelTokenUsedTokenNames(
	group string,
	start, end time.Time,
) ([]string, error)

func GetGlobalGroupChannelTokenUsedTokenNamesMinute

func GetGlobalGroupChannelTokenUsedTokenNamesMinute(
	group string,
	start, end time.Time,
) ([]string, error)

func GetGlobalGroupChannelUsedChannels

func GetGlobalGroupChannelUsedChannels(
	group string,
	groupChannelID int,
	start, end time.Time,
) ([]int, error)

func GetGlobalGroupChannelUsedChannelsMinute

func GetGlobalGroupChannelUsedChannelsMinute(
	group string,
	groupChannelID int,
	start, end time.Time,
) ([]int, error)

func GetGlobalGroupChannelUsedModels

func GetGlobalGroupChannelUsedModels(
	group string,
	groupChannelID int,
	start, end time.Time,
) ([]string, error)

func GetGlobalGroupChannelUsedModelsMinute

func GetGlobalGroupChannelUsedModelsMinute(
	group string,
	groupChannelID int,
	start, end time.Time,
) ([]string, error)

func GetGroupChannelLastRequestTimeMinute

func GetGroupChannelLastRequestTimeMinute(group string, groupChannelID int) (time.Time, error)

func GetGroupChannelLastRequestTimesMinute

func GetGroupChannelLastRequestTimesMinute(
	group string,
	groupChannelIDs []int,
) (map[int]time.Time, error)

func GetGroupChannelTokenUsedModels

func GetGroupChannelTokenUsedModels(
	group, tokenName string,
	start, end time.Time,
) ([]string, error)

func GetGroupChannelTokenUsedModelsMinute

func GetGroupChannelTokenUsedModelsMinute(
	group, tokenName string,
	start, end time.Time,
) ([]string, error)

func GetGroupChannelTokenUsedTokenNames

func GetGroupChannelTokenUsedTokenNames(group string, start, end time.Time) ([]string, error)

func GetGroupChannelTokenUsedTokenNamesMinute

func GetGroupChannelTokenUsedTokenNamesMinute(
	group string,
	start, end time.Time,
) ([]string, error)

func GetGroupChannelUsedChannels

func GetGroupChannelUsedChannels(
	group string,
	groupChannelID int,
	start, end time.Time,
) ([]int, error)

func GetGroupChannelUsedChannelsMinute

func GetGroupChannelUsedChannelsMinute(
	group string,
	groupChannelID int,
	start, end time.Time,
) ([]int, error)

func GetGroupChannelUsedModels

func GetGroupChannelUsedModels(
	group string,
	groupChannelID int,
	start, end time.Time,
) ([]string, error)

func GetGroupChannelUsedModelsMinute

func GetGroupChannelUsedModelsMinute(
	group string,
	groupChannelID int,
	start, end time.Time,
) ([]string, error)

func GetGroupLastRequestTimeMinute

func GetGroupLastRequestTimeMinute(group string) (time.Time, error)

func GetGroupTokenLastRequestTimeMinute

func GetGroupTokenLastRequestTimeMinute(group, token string) (time.Time, error)

func GetGroupTokenLastRequestTimesMinute

func GetGroupTokenLastRequestTimesMinute(
	group string,
	tokenNames []string,
) (map[string]time.Time, error)

func GetGroupUsedModels

func GetGroupUsedModels(group, tokenName string, start, end time.Time) ([]string, error)

func GetGroupUsedModelsMinute

func GetGroupUsedModelsMinute(group, tokenName string, start, end time.Time) ([]string, error)

func GetGroupUsedTokenNames

func GetGroupUsedTokenNames(group string, start, end time.Time) ([]string, error)

func GetGroupUsedTokenNamesMinute

func GetGroupUsedTokenNamesMinute(group string, start, end time.Time) ([]string, error)

func GetIPGroups

func GetIPGroups(threshold int, start, end time.Time) (map[string][]string, error)

func GetModelConfigBool

func GetModelConfigBool(config map[ModelConfigKey]any, key ModelConfigKey) (bool, bool)

func GetModelConfigFloat

func GetModelConfigFloat(config map[ModelConfigKey]any, key ModelConfigKey) (float64, bool)

func GetModelConfigInt

func GetModelConfigInt(config map[ModelConfigKey]any, key ModelConfigKey) (int, bool)

func GetModelConfigStringSlice

func GetModelConfigStringSlice(config map[ModelConfigKey]any, key ModelConfigKey) ([]string, bool)

func GetModelConfigUint

func GetModelConfigUint(config map[ModelConfigKey]any, key ModelConfigKey) (uint64, bool)

func GetModelConfigWithModels

func GetModelConfigWithModels(models []string) ([]string, []string, error)

func GetPublicMCPsEmbedConfig

func GetPublicMCPsEmbedConfig(ids []string) (map[string]MCPEmbeddingConfig, error)

func GetPublicMCPsEnabled

func GetPublicMCPsEnabled(ids []string) ([]string, error)

func GetUsedChannels

func GetUsedChannels(start, end time.Time) ([]int, error)

func GetUsedChannelsMinute

func GetUsedChannelsMinute(start, end time.Time) ([]int, error)

func GetUsedModels

func GetUsedModels(channelID int, start, end time.Time) ([]string, error)

func GetUsedModelsMinute

func GetUsedModelsMinute(channelID int, start, end time.Time) ([]string, error)

func GroupChannelAccessModels

func GroupChannelAccessModels(channel *GroupChannel) []string

func GroupChannelMonitorKey

func GroupChannelMonitorKey(group string, id int) string

func GroupChannelMonitorPrefix

func GroupChannelMonitorPrefix(group string) string

func GroupChannelSupportsModel

func GroupChannelSupportsModel(channel *GroupChannel, modelName string) bool

func HandleNotFound

func HandleNotFound(err error, errMsg ...string) error

func HandleUpdateResult

func HandleUpdateResult(result *gorm.DB, entityName string) error

func HashedStoreID

func HashedStoreID(prefix string, parts ...string) string

func IgnoreNotFound

func IgnoreNotFound(err error) error

func InitDB

func InitDB() error

func InitLogDB

func InitLogDB(batchSize int) error

func InitModelConfigAndChannelCache

func InitModelConfigAndChannelCache() error

func InitOption2DB

func InitOption2DB() error

func InsertToken

func InsertToken(token *Token, autoCreateGroup, ignoreExist bool) error

func IntersectAvailableSets

func IntersectAvailableSets(groupSets, tokenSets []string) []string

func IsClaudeLongContextSummary

func IsClaudeLongContextSummary(modelName string, usage Usage) bool

func MarkAsyncUsageBalanceConsumed

func MarkAsyncUsageBalanceConsumed(info *AsyncUsageInfo) error

func ModelTypeNameToType

func ModelTypeNameToType(typeName string) mode.Mode

ModelTypeNameToType converts a model type name to its numeric type

func NewModelConfig

func NewModelConfig(opts ...ModelConfigOption) map[ModelConfigKey]any

func NormalizeAvailableSets

func NormalizeAvailableSets(sets []string) []string

func NormalizePageParams

func NormalizePageParams(page, perPage int) (int, int)

func NotFoundError

func NotFoundError(errMsg ...string) error

func OnConflictDoNothing

func OnConflictDoNothing() *gorm.DB

func OpenMySQL

func OpenMySQL(dsn string) (*gorm.DB, error)

func OpenPostgreSQL

func OpenPostgreSQL(dsn string) (*gorm.DB, error)

func OpenSQLite

func OpenSQLite(sqlitePath string) (*gorm.DB, error)

func ProcessBatchUpdatesSummary

func ProcessBatchUpdatesSummary()

func PromptCacheStoreID

func PromptCacheStoreID(modelName, promptCacheKey string, keyType CacheKeyType) string

func RangeModelsWithAllowList

func RangeModelsWithAllowList(
	allowedModels []string,
	availableSets []string,
	modelsBySet map[string][]string,
	fn func(model string) bool,
)

func RangeTokenModels

func RangeTokenModels(
	token TokenCache,
	availableSets []string,
	modelsBySet map[string][]string,
	fn func(model string) bool,
)

func RecordConsumeLog

func RecordConsumeLog(
	requestID string,
	createAt time.Time,
	requestAt time.Time,
	retryAt time.Time,
	firstByteAt time.Time,
	group string,
	code int,
	channelID int,
	modelName string,
	tokenID int,
	tokenName string,
	endpoint string,
	content string,
	mode int,
	ip string,
	retryTimes int,
	requestDetail *RequestDetail,
	usage Usage,
	usageContext UsageContext,
	modelPrice Price,
	amountDetail Amount,
	user string,
	metadata map[string]string,
	promptCacheKey string,
	upstreamID string,
	asyncUsageStatus AsyncUsageStatus,
) error

func RecordGroupChannelConsumeLog

func RecordGroupChannelConsumeLog(
	requestID string,
	createAt time.Time,
	requestAt time.Time,
	retryAt time.Time,
	firstByteAt time.Time,
	group string,
	code int,
	groupChannelID int,
	modelName string,
	tokenID int,
	tokenName string,
	endpoint string,
	content string,
	mode int,
	ip string,
	retryTimes int,
	requestDetail *RequestDetail,
	usage Usage,
	usageContext UsageContext,
	modelPrice Price,
	amountDetail Amount,
	user string,
	metadata map[string]string,
	promptCacheKey string,
	upstreamID string,
	asyncUsageStatus AsyncUsageStatus,
) error

func RecordGroupChannelRetryLog

func RecordGroupChannelRetryLog(
	requestID string,
	createAt time.Time,
	requestAt time.Time,
	retryAt time.Time,
	firstByteAt time.Time,
	group string,
	code int,
	groupChannelID int,
	modelName string,
	mode int,
	retryTimes int,
	requestDetail *RequestDetail,
) error

func RecordRetryLog

func RecordRetryLog(
	requestID string,
	createAt time.Time,
	requestAt time.Time,
	retryAt time.Time,
	firstByteAt time.Time,
	code int,
	channelID int,
	modelName string,
	mode int,
	retryTimes int,
	requestDetail *RequestDetail,
) error

func RenewAsyncUsageClaim

func RenewAsyncUsageClaim(
	id int,
	token string,
	leaseUntil time.Time,
) (bool, error)

func ResetTokenPeriodUsage

func ResetTokenPeriodUsage(id int) error

ResetTokenPeriodUsage resets the period usage for a token with concurrency safety This updates PeriodLastUpdateTime and PeriodLastUpdateAmount to current values

func ResolveTokenAvailableSets

func ResolveTokenAvailableSets(groupSets, tokenSets []string) []string

func ResolveTokenGroupChannelAvailableSets

func ResolveTokenGroupChannelAvailableSets(channelSets, tokenSets []string) []string

func ResponseStoreID

func ResponseStoreID(responseID string) string

func RetryClaimedAsyncUsageInfo

func RetryClaimedAsyncUsageInfo(info *AsyncUsageInfo) error

func SaveClaimedAsyncUsageResult

func SaveClaimedAsyncUsageResult(
	info *AsyncUsageInfo,
	usage Usage,
	usageContext UsageContext,
	amount Amount,
) (bool, error)

func SaveGroupModelConfig

func SaveGroupModelConfig(groupModelConfig GroupModelConfig) (err error)

func SaveGroupModelConfigs

func SaveGroupModelConfigs(groupID string, groupModelConfigs []GroupModelConfig) (err error)

func SaveGroupScopeModelConfig

func SaveGroupScopeModelConfig(config GroupScopeModelConfig) (err error)

func SaveGroupScopeModelConfigs

func SaveGroupScopeModelConfigs(group string, configs []GroupScopeModelConfig) (err error)

func SaveModelConfig

func SaveModelConfig(config ModelConfig) (err error)

func SaveModelConfigs

func SaveModelConfigs(configs []ModelConfig) (err error)

func SavePublicMCP

func SavePublicMCP(mcp *PublicMCP) (err error)

func SavePublicMCPReusingParam

func SavePublicMCPReusingParam(param *PublicMCPReusingParam) (err error)

func SavePublicMCPs

func SavePublicMCPs(msps []PublicMCP) (err error)

func SetsFromModelMap

func SetsFromModelMap(modelsBySet map[string][]string) []string

func SortModelConfigsFunc

func SortModelConfigsFunc(i, j ModelConfig) int

func StartBatchProcessorSummary

func StartBatchProcessorSummary(ctx context.Context, wg *sync.WaitGroup)

func StoreChannelKey

func StoreChannelKey(store *StoreCache, scope ChannelScope) string

func StoreID

func StoreID(prefix, id string) string

func String2Int

func String2Int(keyword string) int

func SyncModelConfigAndChannelCache

func SyncModelConfigAndChannelCache(
	ctx context.Context,
	wg *sync.WaitGroup,
	frequency time.Duration,
)

func SyncOptions

func SyncOptions(ctx context.Context, wg *sync.WaitGroup, frequency time.Duration)

func TouchClaimedAsyncUsageInfo

func TouchClaimedAsyncUsageInfo(info *AsyncUsageInfo) error

func TryClaimAsyncUsageInfo

func TryClaimAsyncUsageInfo(
	info *AsyncUsageInfo,
	token string,
	leaseUntil time.Time,
	now time.Time,
) (bool, error)

func UpdateAsyncUsageInfo

func UpdateAsyncUsageInfo(info *AsyncUsageInfo) error

func UpdateChannel

func UpdateChannel(channel *Channel, update *ChannelPatch) (err error)

func UpdateChannelStatusByID

func UpdateChannelStatusByID(id, status int) error

func UpdateChannelUsedAmount

func UpdateChannelUsedAmount(id int, amount float64, requestCount, retryCount int) error

func UpdateGlobalGroupChannel

func UpdateGlobalGroupChannel(channel *GroupChannel) error

func UpdateGlobalGroupChannelStatusByID

func UpdateGlobalGroupChannelStatusByID(id, status int) error

func UpdateGroupChannel

func UpdateGroupChannel(channel *GroupChannel) (err error)

func UpdateGroupChannelGroupUsedAmountAndRequestCount

func UpdateGroupChannelGroupUsedAmountAndRequestCount(
	id string,
	amount float64,
	count int,
) error

func UpdateGroupChannelPatch

func UpdateGroupChannelPatch(channel *GroupChannel, patch *GroupChannelPatch) (err error)

func UpdateGroupChannelStatusByID

func UpdateGroupChannelStatusByID(group string, id, status int) (err error)

func UpdateGroupChannelTokenUsedAmount

func UpdateGroupChannelTokenUsedAmount(id int, amount float64, requestCount int) error

func UpdateGroupChannelUsedAmount

func UpdateGroupChannelUsedAmount(
	group string,
	id int,
	amount float64,
	requestCount, retryCount int,
) (err error)

func UpdateGroupMCP

func UpdateGroupMCP(mcp *GroupMCP) (err error)

UpdateGroupMCP updates an existing GroupMCP

func UpdateGroupMCPStatus

func UpdateGroupMCPStatus(id, groupID string, status GroupMCPStatus) (err error)

func UpdateGroupModelConfig

func UpdateGroupModelConfig(groupModelConfig GroupModelConfig) (err error)

func UpdateGroupModelConfigs

func UpdateGroupModelConfigs(groupID string, groupModelConfigs []GroupModelConfig) (err error)

func UpdateGroupRPMRatio

func UpdateGroupRPMRatio(id string, rpmRatio float64) (err error)

func UpdateGroupStatus

func UpdateGroupStatus(id string, status int) (err error)

func UpdateGroupTPMRatio

func UpdateGroupTPMRatio(id string, tpmRatio float64) (err error)

func UpdateGroupTokenName

func UpdateGroupTokenName(group string, id int, name string) (err error)

func UpdateGroupTokenStatus

func UpdateGroupTokenStatus(group string, id, status int) (err error)

func UpdateGroupUsedAmountAndRequestCount

func UpdateGroupUsedAmountAndRequestCount(id string, amount float64, count int) (err error)

func UpdateGroupsStatus

func UpdateGroupsStatus(ids []string, status int) (rowsAffected int64, err error)

func UpdateLogAsyncUsageFailedByRequestID

func UpdateLogAsyncUsageFailedByRequestID(requestID, message string) error

func UpdateLogAsyncUsageStatusByRequestID

func UpdateLogAsyncUsageStatusByRequestID(
	requestID string,
	status AsyncUsageStatus,
) error

func UpdateLogUsageByRequestID

func UpdateLogUsageByRequestID(
	requestID string,
	usage Usage,
	usageContext UsageContext,
	price Price,
	amount Amount,
) error

func UpdateOption

func UpdateOption(key, value string) error

func UpdateOptions

func UpdateOptions(options map[string]string) error

func UpdatePublicMCP

func UpdatePublicMCP(mcp *PublicMCP) (err error)

UpdatePublicMCP updates an existing MCP

func UpdatePublicMCPReusingParam

func UpdatePublicMCPReusingParam(param *PublicMCPReusingParam) (err error)

UpdatePublicMCPReusingParam updates an existing GroupMCPReusingParam

func UpdatePublicMCPStatus

func UpdatePublicMCPStatus(id string, status PublicMCPStatus) (err error)

func UpdateTokenName

func UpdateTokenName(id int, name string) (err error)

func UpdateTokenStatus

func UpdateTokenStatus(id, status int) (err error)

func UpdateTokenUsedAmount

func UpdateTokenUsedAmount(id int, amount float64, requestCount int) (err error)

func UpsertGroupChannelSummary

func UpsertGroupChannelSummary(unique GroupChannelSummaryUnique, data SummaryData) error

func UpsertGroupChannelSummaryMinute

func UpsertGroupChannelSummaryMinute(
	unique GroupChannelSummaryMinuteUnique,
	data SummaryData,
) error

func UpsertGroupChannelTokenSummary

func UpsertGroupChannelTokenSummary(
	unique GroupChannelTokenSummaryUnique,
	data SummaryData,
) error

func UpsertGroupChannelTokenSummaryMinute

func UpsertGroupChannelTokenSummaryMinute(
	unique GroupChannelTokenSummaryMinuteUnique,
	data SummaryData,
) error

func UpsertGroupScopeModelConfigs

func UpsertGroupScopeModelConfigs(group string, configs []GroupScopeModelConfig) (err error)

func UpsertGroupSummary

func UpsertGroupSummary(unique GroupSummaryUnique, data SummaryData) error

func UpsertGroupSummaryMinute

func UpsertGroupSummaryMinute(unique GroupSummaryMinuteUnique, data SummaryData) error

func UpsertSummary

func UpsertSummary(unique SummaryUnique, data SummaryData) error

func UpsertSummaryMinute

func UpsertSummaryMinute(unique SummaryMinuteUnique, data SummaryData) error

func ValidTokenChannelScope

func ValidTokenChannelScope(scope ChannelScope) bool

func ValidateTokenQuota

func ValidateTokenQuota(token *TokenCache) error

func VideoGenerationStoreID

func VideoGenerationStoreID(generationID string) string

func VideoJobStoreID

func VideoJobStoreID(jobID string) string

Types

type Amount

type Amount struct {
	InputAmount         float64 `json:"input_amount,omitempty"`
	ImageInputAmount    float64 `json:"image_input_amount,omitempty"`
	AudioInputAmount    float64 `json:"audio_input_amount,omitempty"`
	VideoInputAmount    float64 `json:"video_input_amount,omitempty"`
	OutputAmount        float64 `json:"output_amount,omitempty"`
	ImageOutputAmount   float64 `json:"image_output_amount,omitempty"`
	AudioOutputAmount   float64 `json:"audio_output_amount,omitempty"`
	CachedAmount        float64 `json:"cached_amount,omitempty"`
	CacheCreationAmount float64 `json:"cache_creation_amount,omitempty"`
	WebSearchAmount     float64 `json:"web_search_amount,omitempty"`
	UsedAmount          float64 `json:"used_amount,omitempty"`
}

func (*Amount) Add

func (a *Amount) Add(other Amount)

type AsyncUsageInfo

type AsyncUsageInfo struct {
	ID                          int              `gorm:"primaryKey"              json:"id"`
	RequestID                   string           `gorm:"type:char(16);index"     json:"request_id"`
	RequestAt                   time.Time        `                               json:"request_at"`
	Mode                        int              `gorm:"index"                   json:"mode"`
	Model                       string           `gorm:"size:128"                json:"model"`
	ChannelID                   int              `gorm:"index"                   json:"channel_id"`
	BaseURL                     string           `gorm:"type:text"               json:"base_url,omitempty"`
	GroupID                     string           `gorm:"size:64;index"           json:"group_id"`
	TokenID                     int              `gorm:"index"                   json:"token_id"`
	TokenName                   string           `gorm:"size:128"                json:"token_name,omitempty"`
	Price                       Price            `gorm:"embedded"                json:"price"`
	UpstreamID                  string           `gorm:"type:varchar(256);index" json:"upstream_id"`
	Status                      AsyncUsageStatus `gorm:"index;default:1"         json:"status"`
	Usage                       Usage            `gorm:"embedded"                json:"usage"`
	UsageContext                UsageContext     `gorm:"embedded"                json:"usage_context,omitempty"`
	DisableResolutionFuzzyMatch bool             `                               json:"disable_resolution_fuzzy_match,omitempty"`
	Amount                      Amount           `gorm:"embedded"                json:"amount,omitempty"`
	Error                       string           `gorm:"type:text"               json:"error,omitempty"`
	RetryCount                  int              `                               json:"retry_count"`
	BalanceConsumed             bool             `                               json:"balance_consumed"`
	ProcessingToken             string           `gorm:"size:64;index"           json:"-"`
	NextPollAt                  time.Time        `gorm:"index"                   json:"next_poll_at"`
	CreatedAt                   time.Time        `                               json:"created_at"`
	UpdatedAt                   time.Time        `                               json:"updated_at"`
}

func GetPendingAsyncUsages

func GetPendingAsyncUsages(limit int) ([]*AsyncUsageInfo, error)

func GetPendingAsyncUsagesDue

func GetPendingAsyncUsagesDue(
	limit int,
	now time.Time,
) ([]*AsyncUsageInfo, error)

type AsyncUsageStatus

type AsyncUsageStatus int
const (
	AsyncUsageStatusNone AsyncUsageStatus = iota
	AsyncUsageStatusPending
	AsyncUsageStatusCompleted
	AsyncUsageStatusFailed
)

type CacheKeyType

type CacheKeyType string
const (
	CacheKeyTypeStable CacheKeyType = "stable"
	CacheKeyTypeRecent CacheKeyType = "recent"
)

type Channel

type Channel struct {
	DeletedAt               gorm.DeletedAt    `gorm:"index;index:idx_channels_backup_active_id,priority:2"         json:"-"                          yaml:"-"`
	CreatedAt               time.Time         `gorm:"index"                                                        json:"created_at"                 yaml:"-"`
	LastTestErrorAt         time.Time         `                                                                    json:"last_test_error_at"         yaml:"-"`
	ChannelTests            []*ChannelTest    `gorm:"foreignKey:ChannelID;references:ID"                           json:"channel_tests,omitempty"    yaml:"-"`
	BalanceUpdatedAt        time.Time         `                                                                    json:"balance_updated_at"         yaml:"-"`
	ModelMapping            map[string]string `` /* 132-byte string literal not displayed */
	Key                     string            `gorm:"type:text;index:,length:191"                                  json:"key"                        yaml:"key,omitempty"`
	Name                    string            `gorm:"size:64;index"                                                json:"name"                       yaml:"name,omitempty"`
	Remark                  string            `gorm:"size:255;index"                                               json:"remark,omitempty"           yaml:"remark,omitempty"`
	BaseURL                 string            `` /* 127-byte string literal not displayed */
	ProxyURL                string            `` /* 128-byte string literal not displayed */
	Models                  []string          `gorm:"serializer:fastjson;type:text"                                json:"models"                     yaml:"models,omitempty"`
	Balance                 float64           `` /* 126-byte string literal not displayed */
	ID                      int               `gorm:"primaryKey;index:idx_channels_backup_active_id,priority:3"    json:"id"                         yaml:"id,omitempty"`
	UsedAmount              float64           `gorm:"index"                                                        json:"used_amount"                yaml:"-"`
	RequestCount            int               `gorm:"index"                                                        json:"request_count"              yaml:"-"`
	RetryCount              int               `gorm:"index"                                                        json:"retry_count"                yaml:"-"`
	Status                  int               `gorm:"default:1;index"                                              json:"status"                     yaml:"status,omitempty"`
	Type                    ChannelType       `gorm:"default:0;index"                                              json:"type"                       yaml:"type,omitempty"`
	Priority                int32             `` /* 127-byte string literal not displayed */
	BackupOnly              bool              `` /* 130-byte string literal not displayed */
	EnabledAutoBalanceCheck bool              `` /* 145-byte string literal not displayed */
	BalanceThreshold        float64           `` /* 136-byte string literal not displayed */
	SkipTLSVerify           bool              `` /* 134-byte string literal not displayed */
	EnabledNoPermissionBan  bool              `` /* 144-byte string literal not displayed */
	WarnErrorRate           float64           `` /* 134-byte string literal not displayed */
	MaxErrorRate            float64           `` /* 133-byte string literal not displayed */
	Configs                 ChannelConfigs    `` /* 126-byte string literal not displayed */
	Sets                    []string          `gorm:"serializer:fastjson;type:text"                                json:"sets,omitempty"             yaml:"sets,omitempty"`
}

func GetAllChannels

func GetAllChannels() (channels []*Channel, err error)

func GetChannelByID

func GetChannelByID(id int) (*Channel, error)

func GetChannels

func GetChannels(
	page, perPage int,
	filter ChannelFilter,
	order string,
) (channels []*Channel, total int64, err error)

func LoadChannelByID

func LoadChannelByID(id int) (*Channel, error)

func LoadChannels

func LoadChannels() ([]*Channel, error)

func LoadDisabledChannels

func LoadDisabledChannels() ([]*Channel, error)

func LoadEnabledChannels

func LoadEnabledChannels() ([]*Channel, error)

func NewConfigChannels

func NewConfigChannels(yamlConfig *YAMLConfig, status int) []*Channel

NewConfigChannels merges YAML channels with database channels YAML channels are assigned negative IDs to distinguish them from database channels Note: YAML channels are NOT persisted to the database

func SearchChannels

func SearchChannels(
	keyword string,
	page, perPage int,
	filter ChannelFilter,
	order string,
) (channels []*Channel, total int64, err error)

func (*Channel) BeforeDelete

func (c *Channel) BeforeDelete(tx *gorm.DB) (err error)

func (*Channel) GetBalanceThreshold

func (c *Channel) GetBalanceThreshold() float64

func (*Channel) GetPriority

func (c *Channel) GetPriority() int32

func (*Channel) GetSets

func (c *Channel) GetSets() []string

func (*Channel) MarshalJSON

func (c *Channel) MarshalJSON() ([]byte, error)

func (*Channel) UpdateBalance

func (c *Channel) UpdateBalance(balance float64) error

func (*Channel) UpdateModelTest

func (c *Channel) UpdateModelTest(
	testAt time.Time,
	model, actualModel string,
	mode mode.Mode,
	took float64,
	success bool,
	response string,
	code int,
) (*ChannelTest, error)

type ChannelBasicInfo

type ChannelBasicInfo struct {
	ID         int         `json:"id"`
	Name       string      `json:"name"`
	Remark     string      `json:"remark,omitempty"`
	Type       ChannelType `json:"type"`
	Status     int         `json:"status"`
	BackupOnly bool        `json:"backup_only"`
}

func GetChannelsBasicInfoByIDs

func GetChannelsBasicInfoByIDs(ids []int) ([]*ChannelBasicInfo, error)

type ChannelConfigs

type ChannelConfigs map[string]any

func (ChannelConfigs) LoadConfig

func (c ChannelConfigs) LoadConfig(config any) error

type ChannelFilter

type ChannelFilter struct {
	ID         int
	Name       string
	Key        string
	Type       int
	BaseURL    string
	Remark     *string
	BackupOnly *bool
}

type ChannelItem

type ChannelItem struct {
	Channel  `       yaml:",inline"` // Embed Channel to inherit all fields
	TypeName string                  `yaml:"type_name,omitempty"` // Alternative to Type (e.g., "openai", "claude")
}

ChannelItem wraps Channel for YAML configuration Adds TypeName field for human-readable channel type specification

func (*ChannelItem) GetChannelType

func (c *ChannelItem) GetChannelType() ChannelType

GetChannelType returns the channel type, converting from TypeName if Type is not set

type ChannelPatch

type ChannelPatch struct {
	Type                    *ChannelType       `json:"type,omitempty"`
	Name                    *string            `json:"name,omitempty"`
	Remark                  *string            `json:"remark,omitempty"`
	Key                     *string            `json:"key,omitempty"`
	BaseURL                 *string            `json:"base_url,omitempty"`
	ProxyURL                *string            `json:"proxy_url,omitempty"`
	Models                  *[]string          `json:"models,omitempty"                     gorm:"serializer:fastjson;type:text"`
	ModelMapping            *map[string]string `json:"model_mapping,omitempty"              gorm:"serializer:fastjson;type:text"`
	Configs                 *ChannelConfigs    `json:"configs,omitempty"                    gorm:"serializer:fastjson;type:text"`
	Priority                *int32             `json:"priority,omitempty"`
	BackupOnly              *bool              `json:"backup_only,omitempty"`
	Sets                    *[]string          `json:"sets,omitempty"                       gorm:"serializer:fastjson;type:text"`
	EnabledAutoBalanceCheck *bool              `json:"enabled_auto_balance_check,omitempty"`
	SkipTLSVerify           *bool              `json:"skip_tls_verify,omitempty"`
	EnabledNoPermissionBan  *bool              `json:"enabled_no_permission_ban,omitempty"`
	WarnErrorRate           *float64           `json:"warn_error_rate,omitempty"`
	MaxErrorRate            *float64           `json:"max_error_rate,omitempty"`
	BalanceThreshold        *float64           `json:"balance_threshold,omitempty"`
}

ChannelPatch separates optional writes from stored channel values. Nil pointers leave columns unchanged; non-nil zero values are persisted.

type ChannelScope

type ChannelScope string
const (
	ChannelScopeGlobal ChannelScope = "global"
	ChannelScopeGroup  ChannelScope = "group"
)

func NormalizeChannelScope

func NormalizeChannelScope(scope ChannelScope) ChannelScope

func ParseChannelScope

func ParseChannelScope(value string) ChannelScope

func (ChannelScope) MarshalBinary

func (s ChannelScope) MarshalBinary() ([]byte, error)

func (*ChannelScope) ScanRedis

func (s *ChannelScope) ScanRedis(value string) error

type ChannelTest

type ChannelTest struct {
	TestAt      time.Time   `json:"test_at"`
	Model       string      `json:"model"        gorm:"size:128;primaryKey"`
	ActualModel string      `json:"actual_model" gorm:"size:128"`
	Response    string      `json:"response"     gorm:"type:text"`
	ChannelName string      `json:"channel_name" gorm:"size:64"`
	ChannelType ChannelType `json:"channel_type"`
	ChannelID   int         `json:"channel_id"   gorm:"primaryKey"`
	Took        float64     `json:"took"`
	Success     bool        `json:"success"`
	Mode        mode.Mode   `json:"mode"`
	Code        int         `json:"code"`
}

func (*ChannelTest) MarshalJSON

func (ct *ChannelTest) MarshalJSON() ([]byte, error)

type ChannelType

type ChannelType int
const (
	ChannelTypeOpenAI                  ChannelType = 1
	ChannelTypeAzure                   ChannelType = 3
	ChannelTypeAzure2                  ChannelType = 4
	ChannelTypeGoogleGeminiOpenAI      ChannelType = 12
	ChannelTypeBaiduV2                 ChannelType = 13
	ChannelTypeAnthropic               ChannelType = 14
	ChannelTypeBaidu                   ChannelType = 15
	ChannelTypeZhipu                   ChannelType = 16
	ChannelTypeAli                     ChannelType = 17
	ChannelTypeXunfei                  ChannelType = 18
	ChannelTypeAI360                   ChannelType = 19
	ChannelTypeOpenRouter              ChannelType = 20
	ChannelTypeTencent                 ChannelType = 23
	ChannelTypeGoogleGemini            ChannelType = 24
	ChannelTypeMoonshot                ChannelType = 25
	ChannelTypeBaichuan                ChannelType = 26
	ChannelTypeMinimax                 ChannelType = 27
	ChannelTypeMistral                 ChannelType = 28
	ChannelTypeGroq                    ChannelType = 29
	ChannelTypeOllama                  ChannelType = 30
	ChannelTypeLingyiwanwu             ChannelType = 31
	ChannelTypeStepfun                 ChannelType = 32
	ChannelTypeAWS                     ChannelType = 33
	ChannelTypeCoze                    ChannelType = 34
	ChannelTypeCohere                  ChannelType = 35
	ChannelTypeDeepseek                ChannelType = 36
	ChannelTypeCloudflare              ChannelType = 37
	ChannelTypeDoubao                  ChannelType = 40
	ChannelTypeNovita                  ChannelType = 41
	ChannelTypeVertexAI                ChannelType = 42
	ChannelTypeSiliconflow             ChannelType = 43
	ChannelTypeDoubaoAudio             ChannelType = 44
	ChannelTypeXAI                     ChannelType = 45
	ChannelTypeDoc2x                   ChannelType = 46
	ChannelTypeJina                    ChannelType = 47
	ChannelTypeTextEmbeddingsInference ChannelType = 48
	ChannelTypeQianfan                 ChannelType = 49
	ChannelTypeSangforAICP             ChannelType = 50
	ChannelTypeStreamlake              ChannelType = 51
	ChannelTypeZhipuCoding             ChannelType = 52
	ChannelTypeFake                    ChannelType = 53
	ChannelTypeAntLing                 ChannelType = 54
	ChannelTypeFakeError               ChannelType = 55
	ChannelTypeQwenCloud               ChannelType = 56
	ChannelTypeAIProxyHZH              ChannelType = 57
	ChannelTypeAIProxyUSW1             ChannelType = 58
	ChannelTypeTokenDance              ChannelType = 59
	ChannelTypeVoyage                  ChannelType = 60
)

func (ChannelType) String

func (c ChannelType) String() string

type ChannelUpdate

type ChannelUpdate struct {
	Amount     decimal.Decimal
	Count      int
	RetryCount int
}

type ChartData

type ChartData struct {
	Timestamp int64 `json:"timestamp"`
	SummaryDataSet
	ServiceTierFlex     SummaryDataSet `json:"service_tier_flex,omitempty"     gorm:"embedded;embeddedPrefix:service_tier_flex_"`
	ServiceTierPriority SummaryDataSet `json:"service_tier_priority,omitempty" gorm:"embedded;embeddedPrefix:service_tier_priority_"`
	ClaudeLongContext   SummaryDataSet `json:"claude_long_context,omitempty"   gorm:"embedded;embeddedPrefix:claude_long_context_"`
}

type CodeType

type CodeType string
const (
	CodeTypeAll     CodeType = "all"
	CodeTypeSuccess CodeType = "success"
	CodeTypeError   CodeType = "error"
)

type ConditionalPrice

type ConditionalPrice struct {
	Condition PriceCondition `json:"condition"`
	Price     Price          `json:"price"`
}

type ConsumeError

type ConsumeError struct {
	RequestAt  time.Time       `gorm:"index;index:idx_consume_error_group_reqat,priority:2"         json:"request_at"`
	CreatedAt  time.Time       `                                                                    json:"created_at"`
	GroupID    string          `gorm:"size:64;index;index:idx_consume_error_group_reqat,priority:1" json:"group_id"`
	RequestID  string          `gorm:"type:char(16);index"                                          json:"request_id"`
	TokenName  EmptyNullString `gorm:"size:32;not null"                                             json:"token_name"`
	Model      string          `gorm:"size:128"                                                     json:"model"`
	Content    string          `gorm:"type:text"                                                    json:"content"`
	ID         int             `gorm:"primaryKey"                                                   json:"id"`
	UsedAmount float64         `                                                                    json:"used_amount"`
	TokenID    int             `                                                                    json:"token_id"`
}

func SearchConsumeError

func SearchConsumeError(
	keyword, requestID, group, tokenName, model string,
	tokenID, page, perPage int,
	order string,
) ([]*ConsumeError, int64, error)

func (*ConsumeError) MarshalJSON

func (c *ConsumeError) MarshalJSON() ([]byte, error)

type ConsumptionRankingItem

type ConsumptionRankingItem struct {
	GroupID      string  `json:"group_id,omitempty"   gorm:"column:group_id"`
	ChannelID    int     `json:"channel_id,omitempty" gorm:"column:channel_id"`
	Model        string  `json:"model,omitempty"      gorm:"column:model"`
	RequestCount int64   `json:"request_count"        gorm:"column:request_count"`
	UsedAmount   float64 `json:"used_amount"          gorm:"column:used_amount"`
	InputTokens  int64   `json:"input_tokens"         gorm:"column:input_tokens"`
	OutputTokens int64   `json:"output_tokens"        gorm:"column:output_tokens"`
	TotalTokens  int64   `json:"total_tokens"         gorm:"column:total_tokens"`
}

func GetConsumptionRanking

func GetConsumptionRanking(
	rankingType ConsumptionRankingType,
	start, end time.Time,
	page, perPage int,
	order string,
) ([]ConsumptionRankingItem, int64, string, error)

type ConsumptionRankingType

type ConsumptionRankingType string
const (
	ConsumptionRankingTypeGroup   ConsumptionRankingType = "group"
	ConsumptionRankingTypeChannel ConsumptionRankingType = "channel"
	ConsumptionRankingTypeModel   ConsumptionRankingType = "model"
)

type Count

type Count struct {
	RequestCount       int64         `json:"request_count"`
	RetryCount         ZeroNullInt64 `json:"retry_count,omitempty"`
	ExceptionCount     ZeroNullInt64 `json:"exception_count,omitempty"`
	Status2xxCount     ZeroNullInt64 `json:"status_2xx_count,omitempty"`
	Status4xxCount     ZeroNullInt64 `json:"status_4xx_count,omitempty"`
	Status5xxCount     ZeroNullInt64 `json:"status_5xx_count,omitempty"`
	StatusOtherCount   ZeroNullInt64 `json:"status_other_count,omitempty"`
	Status400Count     ZeroNullInt64 `json:"status_400_count,omitempty"`
	Status429Count     ZeroNullInt64 `json:"status_429_count,omitempty"`
	Status500Count     ZeroNullInt64 `json:"status_500_count,omitempty"`
	CacheHitCount      ZeroNullInt64 `json:"cache_hit_count,omitempty"`
	CacheCreationCount ZeroNullInt64 `json:"cache_creation_count,omitempty"`
}

func (*Count) Add

func (c *Count) Add(other Count)

func (*Count) AddRequest

func (c *Count) AddRequest(status int, isRetry bool)

type DashboardResponse

type DashboardResponse struct {
	ChartData []ChartData `json:"chart_data"`

	RPM int64 `json:"rpm"`
	TPM int64 `json:"tpm"`

	MaxRPM int64 `json:"max_rpm"`
	MaxTPM int64 `json:"max_tpm"`

	TotalCount int64 `json:"total_count"` // use Count.RequestCount instead
	SummaryDataSet
	ServiceTierFlex     SummaryDataSet `json:"service_tier_flex,omitempty"     gorm:"embedded;embeddedPrefix:service_tier_flex_"`
	ServiceTierPriority SummaryDataSet `json:"service_tier_priority,omitempty" gorm:"embedded;embeddedPrefix:service_tier_priority_"`
	ClaudeLongContext   SummaryDataSet `json:"claude_long_context,omitempty"   gorm:"embedded;embeddedPrefix:claude_long_context_"`

	Channels []int    `json:"channels,omitempty"`
	Models   []string `json:"models,omitempty"`
}

func GetDashboardData

func GetDashboardData(
	start,
	end time.Time,
	modelName string,
	channelID int,
	timeSpan TimeSpanType,
	timezone *time.Location,
	fields SummarySelectFields,
) (*DashboardResponse, error)

func GetGlobalGroupChannelDashboardData

func GetGlobalGroupChannelDashboardData(
	group string,
	groupChannelID int,
	modelName string,
	start, end time.Time,
	timeSpan TimeSpanType,
	timezone *time.Location,
	fields SummarySelectFields,
) (*DashboardResponse, error)

func GetGroupChannelDashboardData

func GetGroupChannelDashboardData(
	group string,
	groupChannelID int,
	modelName string,
	start, end time.Time,
	timeSpan TimeSpanType,
	timezone *time.Location,
	fields SummarySelectFields,
) (*DashboardResponse, error)

type DashboardV2Response

type DashboardV2Response struct {
	TimeSeries []TimeSummaryDataV2 `json:"time_series"`
	RPM        int64               `json:"rpm"`
	TPM        int64               `json:"tpm"`
	Channels   []int               `json:"channels,omitempty"`
	Models     []string            `json:"models,omitempty"`
}

func GetDashboardV2Data

func GetDashboardV2Data(
	channelID int,
	modelName string,
	start, end time.Time,
	timeSpan TimeSpanType,
	timezone *time.Location,
	fields SummarySelectFields,
) (*DashboardV2Response, error)

func GetGlobalGroupChannelDashboardV2Data

func GetGlobalGroupChannelDashboardV2Data(
	group string,
	groupChannelID int,
	modelName string,
	start, end time.Time,
	timeSpan TimeSpanType,
	timezone *time.Location,
	fields SummarySelectFields,
) (*DashboardV2Response, error)

func GetGroupChannelDashboardV2Data

func GetGroupChannelDashboardV2Data(
	group string,
	groupChannelID int,
	modelName string,
	start, end time.Time,
	timeSpan TimeSpanType,
	timezone *time.Location,
	fields SummarySelectFields,
) (*DashboardV2Response, error)

type DashboardV3Response

type DashboardV3Response = DashboardV2Response

func GetDashboardV3Data

func GetDashboardV3Data(
	channelID int,
	modelName string,
	start, end time.Time,
	timeSpan TimeSpanType,
	timezone *time.Location,
	fields SummarySelectFields,
) (*DashboardV3Response, error)

V3 wrapper functions - same as V2 since types are aliases

func GetGlobalGroupChannelDashboardV3Data

func GetGlobalGroupChannelDashboardV3Data(
	group string,
	groupChannelID int,
	modelName string,
	start, end time.Time,
	timeSpan TimeSpanType,
	timezone *time.Location,
	fields SummarySelectFields,
) (*DashboardV3Response, error)

func GetGroupChannelDashboardV3Data

func GetGroupChannelDashboardV3Data(
	group string,
	groupChannelID int,
	modelName string,
	start, end time.Time,
	timeSpan TimeSpanType,
	timezone *time.Location,
	fields SummarySelectFields,
) (*DashboardV3Response, error)

type EmptyNullString

type EmptyNullString string

func (*EmptyNullString) Scan

func (ns *EmptyNullString) Scan(value any) error

Scan implements the [Scanner] interface.

func (EmptyNullString) String

func (ns EmptyNullString) String() string

func (EmptyNullString) Value

func (ns EmptyNullString) Value() (driver.Value, error)

Value implements the driver.Valuer interface.

type GetGroupChannelLogsResult

type GetGroupChannelLogsResult struct {
	Logs       []*GroupChannelLog `json:"logs"`
	Total      int64              `json:"total"`
	Models     []string           `json:"models,omitempty"`
	TokenNames []string           `json:"token_names"`
}

func GetGlobalGroupChannelLogs

func GetGlobalGroupChannelLogs(
	group string,
	startTimestamp time.Time,
	endTimestamp time.Time,
	modelName string,
	requestID string,
	upstreamID string,
	tokenID int,
	tokenName string,
	channelID int,
	order string,
	codeType CodeType,
	code int,
	withBody bool,
	ip string,
	user string,
	page int,
	perPage int,
) (*GetGroupChannelLogsResult, error)

func GetGroupChannelLogs

func GetGroupChannelLogs(
	group string,
	startTimestamp time.Time,
	endTimestamp time.Time,
	modelName string,
	requestID string,
	upstreamID string,
	tokenID int,
	tokenName string,
	channelID int,
	order string,
	codeType CodeType,
	code int,
	withBody bool,
	ip string,
	user string,
	page int,
	perPage int,
) (*GetGroupChannelLogsResult, error)

func SearchGlobalGroupChannelLogs

func SearchGlobalGroupChannelLogs(
	group string,
	keyword string,
	requestID string,
	upstreamID string,
	tokenID int,
	tokenName string,
	modelName string,
	startTimestamp time.Time,
	endTimestamp time.Time,
	channelID int,
	order string,
	codeType CodeType,
	code int,
	withBody bool,
	ip string,
	user string,
	page int,
	perPage int,
) (*GetGroupChannelLogsResult, error)

func SearchGroupChannelLogs

func SearchGroupChannelLogs(
	group string,
	keyword string,
	requestID string,
	upstreamID string,
	tokenID int,
	tokenName string,
	modelName string,
	startTimestamp time.Time,
	endTimestamp time.Time,
	channelID int,
	order string,
	codeType CodeType,
	code int,
	withBody bool,
	ip string,
	user string,
	page int,
	perPage int,
) (*GetGroupChannelLogsResult, error)

type GetGroupLogsResult

type GetGroupLogsResult struct {
	GetLogsResult
	TokenNames []string `json:"token_names"`
}

func GetGroupLogs

func GetGroupLogs(
	group string,
	startTimestamp time.Time,
	endTimestamp time.Time,
	modelName string,
	requestID string,
	upstreamID string,
	tokenID int,
	tokenName string,
	channelID int,
	order string,
	codeType CodeType,
	code int,
	withBody bool,
	ip string,
	user string,
	page int,
	perPage int,
) (*GetGroupLogsResult, error)

func SearchGroupLogs

func SearchGroupLogs(
	group string,
	keyword string,
	requestID string,
	upstreamID string,
	tokenID int,
	tokenName string,
	modelName string,
	startTimestamp time.Time,
	endTimestamp time.Time,
	channelID int,
	order string,
	codeType CodeType,
	code int,
	withBody bool,
	ip string,
	user string,
	page int,
	perPage int,
) (*GetGroupLogsResult, error)

type GetLogsResult

type GetLogsResult struct {
	Logs     []*Log   `json:"logs"`
	Total    int64    `json:"total"`
	Channels []int    `json:"channels,omitempty"`
	Models   []string `json:"models,omitempty"`
}

func GetLogs

func GetLogs(
	startTimestamp time.Time,
	endTimestamp time.Time,
	modelName string,
	requestID string,
	upstreamID string,
	channelID int,
	order string,
	codeType CodeType,
	code int,
	withBody bool,
	ip string,
	user string,
	page int,
	perPage int,
) (*GetLogsResult, error)

func SearchLogs

func SearchLogs(
	keyword string,
	requestID string,
	upstreamID string,
	group string,
	tokenID int,
	tokenName string,
	modelName string,
	startTimestamp time.Time,
	endTimestamp time.Time,
	channelID int,
	order string,
	codeType CodeType,
	code int,
	withBody bool,
	ip string,
	user string,
	page int,
	perPage int,
) (*GetLogsResult, error)

type Group

type Group struct {
	CreatedAt                time.Time               `json:"created_at"`
	ID                       string                  `json:"id"                          gorm:"size:64;primaryKey"`
	Tokens                   []Token                 `json:"-"                           gorm:"foreignKey:GroupID"`
	GroupModelConfigs        []GroupModelConfig      `json:"-"                           gorm:"foreignKey:GroupID"`
	PublicMCPReusingParams   []PublicMCPReusingParam `json:"-"                           gorm:"foreignKey:GroupID"`
	GroupMCPs                []GroupMCP              `json:"-"                           gorm:"foreignKey:GroupID"`
	Status                   int                     `json:"status"                      gorm:"default:1;index"`
	RPMRatio                 float64                 `json:"rpm_ratio,omitempty"         gorm:"index"`
	TPMRatio                 float64                 `json:"tpm_ratio,omitempty"         gorm:"index"`
	UsedAmount               float64                 `json:"used_amount"                 gorm:"index"`
	RequestCount             int                     `json:"request_count"               gorm:"index"`
	GroupChannelUsedAmount   float64                 `json:"group_channel_used_amount"   gorm:"index"`
	GroupChannelRequestCount int                     `json:"group_channel_request_count" gorm:"index"`
	AvailableSets            []string                `json:"available_sets,omitempty"    gorm:"serializer:fastjson;type:text"`

	BalanceAlertEnabled   bool    `gorm:"default:false" json:"balance_alert_enabled"`
	BalanceAlertThreshold float64 `gorm:"default:0"     json:"balance_alert_threshold"`
}

func GetGroupByID

func GetGroupByID(id string, preloadGroupModelConfigs bool) (*Group, error)

func GetGroups

func GetGroups(
	page, perPage int,
	order string,
	onlyDisabled bool,
) (groups []*Group, total int64, err error)

func SearchGroup

func SearchGroup(
	keyword string,
	page, perPage int,
	order string,
	status int,
) (groups []*Group, total int64, err error)

func UpdateGroup

func UpdateGroup(id string, update UpdateGroupRequest) (group *Group, err error)

func (*Group) BeforeDelete

func (g *Group) BeforeDelete(tx *gorm.DB) (err error)

func (*Group) BeforeSave

func (g *Group) BeforeSave(_ *gorm.DB) error

func (*Group) ToGroupCache

func (g *Group) ToGroupCache() *GroupCache

type GroupCache

type GroupCache struct {
	ID            string                   `json:"-"              redis:"-"`
	Status        int                      `json:"status"         redis:"st"`
	UsedAmount    float64                  `json:"used_amount"    redis:"ua"`
	RPMRatio      float64                  `json:"rpm_ratio"      redis:"rpm_r"`
	TPMRatio      float64                  `json:"tpm_ratio"      redis:"tpm_r"`
	AvailableSets redisStringSlice         `json:"available_sets" redis:"ass"`
	ModelConfigs  redisGroupModelConfigMap `json:"model_configs"  redis:"mc"`

	BalanceAlertEnabled   bool    `json:"balance_alert_enabled"   redis:"bae"`
	BalanceAlertThreshold float64 `json:"balance_alert_threshold" redis:"bat"`
}

func CacheGetGroup

func CacheGetGroup(id string) (*GroupCache, error)

func (*GroupCache) GetAvailableSets

func (g *GroupCache) GetAvailableSets() []string

type GroupChannel

type GroupChannel struct {
	Remark                 string              `gorm:"size:255;index"                          json:"remark,omitempty"              yaml:"remark,omitempty"`
	BackupOnly             bool                `gorm:"default:false;index"                     json:"backup_only"                   yaml:"backup_only,omitempty"`
	WarnErrorRate          float64             `                                               json:"warn_error_rate"               yaml:"warn_error_rate,omitempty"`
	DeletedAt              gorm.DeletedAt      `gorm:"index"                                   json:"-"                             yaml:"-"`
	CreatedAt              time.Time           `gorm:"index"                                   json:"created_at"                    yaml:"-"`
	LastTestErrorAt        time.Time           `                                               json:"last_test_error_at"            yaml:"-"`
	GroupChannelTests      []*GroupChannelTest `gorm:"foreignKey:GroupChannelID;references:ID" json:"group_channel_tests,omitempty" yaml:"-"`
	ModelMapping           map[string]string   `gorm:"serializer:fastjson;type:text"           json:"model_mapping"                 yaml:"model_mapping,omitempty"`
	Key                    string              `gorm:"type:text;index:,length:191"             json:"key"                           yaml:"key,omitempty"`
	GroupID                string              `gorm:"size:64;not null;index"                  json:"group_id"                      yaml:"group_id,omitempty"`
	Name                   string              `gorm:"size:64;index"                           json:"name"                          yaml:"name,omitempty"`
	BaseURL                string              `gorm:"size:128;index"                          json:"base_url"                      yaml:"base_url,omitempty"`
	ProxyURL               string              `gorm:"size:255"                                json:"proxy_url"                     yaml:"proxy_url,omitempty"`
	Models                 []string            `gorm:"serializer:fastjson;type:text"           json:"models"                        yaml:"models,omitempty"`
	ID                     int                 `gorm:"primaryKey"                              json:"id"                            yaml:"id,omitempty"`
	UsedAmount             float64             `gorm:"index"                                   json:"used_amount"                   yaml:"-"`
	RequestCount           int                 `gorm:"index"                                   json:"request_count"                 yaml:"-"`
	RetryCount             int                 `gorm:"index"                                   json:"retry_count"                   yaml:"-"`
	Status                 int                 `gorm:"default:1;index"                         json:"status"                        yaml:"status,omitempty"`
	Type                   ChannelType         `gorm:"default:0;index"                         json:"type"                          yaml:"type,omitempty"`
	Priority               int32               `                                               json:"priority"                      yaml:"priority,omitempty"`
	SkipTLSVerify          bool                `                                               json:"skip_tls_verify"               yaml:"skip_tls_verify,omitempty"`
	EnabledNoPermissionBan bool                `` /* 126-byte string literal not displayed */
	MaxErrorRate           float64             `                                               json:"max_error_rate"                yaml:"max_error_rate,omitempty"`
	Configs                ChannelConfigs      `gorm:"serializer:fastjson;type:text"           json:"configs,omitempty"             yaml:"configs,omitempty"`
	Sets                   []string            `gorm:"serializer:fastjson;type:text"           json:"sets,omitempty"                yaml:"sets,omitempty"`
}

func GetAllGlobalGroupChannels

func GetAllGlobalGroupChannels(group string) ([]*GroupChannel, error)

func GetAllGroupChannels

func GetAllGroupChannels(group string) ([]*GroupChannel, error)

func GetGlobalGroupChannelByID

func GetGlobalGroupChannelByID(id int) (*GroupChannel, error)

func GetGlobalGroupChannels

func GetGlobalGroupChannels(
	group string,
	page, perPage, id int,
	name, key string,
	channelType int,
	baseURL, order string,
	filter ...GroupChannelFilter,
) (channels []*GroupChannel, total int64, err error)

func GetGroupChannelByID

func GetGroupChannelByID(group string, id int) (*GroupChannel, error)

func GetGroupChannels

func GetGroupChannels(
	group string,
	page, perPage, id int,
	name, key string,
	channelType int,
	baseURL, order string,
	filter ...GroupChannelFilter,
) (channels []*GroupChannel, total int64, err error)

func LoadEnabledGlobalGroupChannels

func LoadEnabledGlobalGroupChannels(group string) ([]*GroupChannel, error)

func LoadEnabledGroupChannels

func LoadEnabledGroupChannels(group string) ([]*GroupChannel, error)

func LoadGlobalGroupChannelByID

func LoadGlobalGroupChannelByID(id int) (*GroupChannel, error)

func LoadGlobalGroupChannels

func LoadGlobalGroupChannels(group string) ([]*GroupChannel, error)

func LoadGroupChannelByID

func LoadGroupChannelByID(group string, id int) (*GroupChannel, error)

func LoadGroupChannels

func LoadGroupChannels(group string) ([]*GroupChannel, error)

func SearchGlobalGroupChannels

func SearchGlobalGroupChannels(
	group, keyword string,
	page, perPage, id int,
	name, key string,
	channelType int,
	baseURL, order string,
	filter ...GroupChannelFilter,
) (channels []*GroupChannel, total int64, err error)

func SearchGroupChannels

func SearchGroupChannels(
	group, keyword string,
	page, perPage, id int,
	name, key string,
	channelType int,
	baseURL, order string,
	filter ...GroupChannelFilter,
) (channels []*GroupChannel, total int64, err error)

func (*GroupChannel) BeforeCreate

func (c *GroupChannel) BeforeCreate(_ *gorm.DB) error

func (*GroupChannel) BeforeDelete

func (c *GroupChannel) BeforeDelete(tx *gorm.DB) error

func (*GroupChannel) BeforeUpdate

func (c *GroupChannel) BeforeUpdate(tx *gorm.DB) error

func (*GroupChannel) GetPriority

func (c *GroupChannel) GetPriority() int32

func (*GroupChannel) GetSets

func (c *GroupChannel) GetSets() []string

func (*GroupChannel) MarshalJSON

func (c *GroupChannel) MarshalJSON() ([]byte, error)

func (*GroupChannel) ToChannel

func (c *GroupChannel) ToChannel() *Channel

func (*GroupChannel) UpdateModelTest

func (c *GroupChannel) UpdateModelTest(
	testAt time.Time,
	model, actualModel string,
	mode mode.Mode,
	took float64,
	success bool,
	response string,
	code int,
) (*GroupChannelTest, error)

type GroupChannelBasicInfo

type GroupChannelBasicInfo struct {
	GroupID    string      `json:"group_id"`
	Name       string      `json:"name"`
	Remark     string      `json:"remark,omitempty"`
	BackupOnly bool        `json:"backup_only"`
	Status     int         `json:"status"`
	ID         int         `json:"id"`
	Type       ChannelType `json:"type"`
}

func GetGlobalGroupChannelsBasicInfoByIDs

func GetGlobalGroupChannelsBasicInfoByIDs(ids []int) ([]GroupChannelBasicInfo, error)

func GetGroupChannelsBasicInfoByIDs

func GetGroupChannelsBasicInfoByIDs(
	group string,
	ids []int,
) ([]GroupChannelBasicInfo, error)

type GroupChannelFilter

type GroupChannelFilter struct {
	Remark     *string
	BackupOnly *bool
}

type GroupChannelLog

type GroupChannelLog struct {
	RequestDetail    *GroupChannelRequestDetail `gorm:"foreignKey:LogID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;" json:"request_detail,omitempty"`
	RequestAt        time.Time                  `                                                                      json:"request_at"`
	RetryAt          time.Time                  `                                                                      json:"retry_at,omitempty"`
	TTFBMilliseconds ZeroNullInt64              `                                                                      json:"ttfb_milliseconds,omitempty"`
	CreatedAt        time.Time                  `gorm:"autoCreateTime;index"                                           json:"created_at"`
	TokenName        string                     `gorm:"size:32"                                                        json:"token_name,omitempty"`
	Endpoint         EmptyNullString            `gorm:"size:64"                                                        json:"endpoint,omitempty"`
	Content          EmptyNullString            `gorm:"type:text"                                                      json:"content,omitempty"`
	GroupID          string                     `gorm:"size:64;index"                                                  json:"group,omitempty"`
	Model            string                     `gorm:"size:128;index"                                                 json:"model"`
	RequestID        EmptyNullString            `gorm:"type:char(16);index:,where:request_id is not null"              json:"request_id"`
	UpstreamID       EmptyNullString            `gorm:"type:varchar(256)"                                              json:"upstream_id,omitempty"`
	AsyncUsageStatus AsyncUsageStatus           `                                                                      json:"async_usage_status,omitempty"`
	ID               int                        `gorm:"primaryKey"                                                     json:"id"`
	TokenID          int                        `gorm:"index"                                                          json:"token_id,omitempty"`
	GroupChannelID   int                        `gorm:"index"                                                          json:"group_channel_id,omitempty"`
	Code             int                        `gorm:"index"                                                          json:"code,omitempty"`
	Mode             int                        `                                                                      json:"mode,omitempty"`
	IP               EmptyNullString            `gorm:"size:45;index:,where:ip is not null"                            json:"ip,omitempty"`
	RetryTimes       ZeroNullInt64              `                                                                      json:"retry_times,omitempty"`
	Price            Price                      `gorm:"embedded"                                                       json:"price,omitempty"`
	Usage            Usage                      `gorm:"embedded"                                                       json:"usage,omitempty"`
	UsageContext     UsageContext               `gorm:"embedded"                                                       json:"usage_context,omitempty"`
	Amount           Amount                     `gorm:"embedded"                                                       json:"amount,omitempty"`
	PromptCacheKey   EmptyNullString            `gorm:"type:text"                                                      json:"prompt_cache_key,omitempty"`
	User             EmptyNullString            `gorm:"type:text"                                                      json:"user,omitempty"`
	Metadata         map[string]string          `gorm:"serializer:fastjson;type:text"                                  json:"metadata,omitempty"`
}

func ExportGlobalGroupChannelLogs

func ExportGlobalGroupChannelLogs(
	group string,
	startTimestamp time.Time,
	endTimestamp time.Time,
	modelName string,
	requestID string,
	upstreamID string,
	tokenID int,
	tokenName string,
	channelID int,
	order string,
	codeType CodeType,
	code int,
	withBody bool,
	ip string,
	user string,
	maxEntries int,
) ([]*GroupChannelLog, error)

func ExportGlobalGroupChannelLogsRange

func ExportGlobalGroupChannelLogsRange(
	group string,
	startTimestamp time.Time,
	endExclusive time.Time,
	modelName string,
	requestID string,
	upstreamID string,
	tokenID int,
	tokenName string,
	channelID int,
	order string,
	codeType CodeType,
	code int,
	withBody bool,
	ip string,
	user string,
	maxEntries int,
) ([]*GroupChannelLog, error)

func ExportGroupChannelLogs

func ExportGroupChannelLogs(
	group string,
	startTimestamp time.Time,
	endTimestamp time.Time,
	modelName string,
	requestID string,
	upstreamID string,
	tokenID int,
	tokenName string,
	channelID int,
	order string,
	codeType CodeType,
	code int,
	withBody bool,
	ip string,
	user string,
	maxEntries int,
) ([]*GroupChannelLog, error)

func ExportGroupChannelLogsRange

func ExportGroupChannelLogsRange(
	group string,
	startTimestamp time.Time,
	endExclusive time.Time,
	modelName string,
	requestID string,
	upstreamID string,
	tokenID int,
	tokenName string,
	channelID int,
	order string,
	codeType CodeType,
	code int,
	withBody bool,
	ip string,
	user string,
	maxEntries int,
) ([]*GroupChannelLog, error)

func (*GroupChannelLog) BeforeCreate

func (l *GroupChannelLog) BeforeCreate(_ *gorm.DB) error

func (*GroupChannelLog) MarshalJSON

func (l *GroupChannelLog) MarshalJSON() ([]byte, error)

type GroupChannelPatch

type GroupChannelPatch struct {
	Type                   *ChannelType       `json:"type,omitempty"`
	Name                   *string            `json:"name,omitempty"`
	Remark                 *string            `json:"remark,omitempty"`
	Key                    *string            `json:"key,omitempty"`
	BaseURL                *string            `json:"base_url,omitempty"`
	ProxyURL               *string            `json:"proxy_url,omitempty"`
	Models                 *[]string          `json:"models,omitempty"                    gorm:"serializer:fastjson;type:text"`
	ModelMapping           *map[string]string `json:"model_mapping,omitempty"             gorm:"serializer:fastjson;type:text"`
	Configs                *ChannelConfigs    `json:"configs,omitempty"                   gorm:"serializer:fastjson;type:text"`
	Priority               *int32             `json:"priority,omitempty"`
	BackupOnly             *bool              `json:"backup_only,omitempty"`
	Sets                   *[]string          `json:"sets,omitempty"                      gorm:"serializer:fastjson;type:text"`
	SkipTLSVerify          *bool              `json:"skip_tls_verify,omitempty"`
	EnabledNoPermissionBan *bool              `json:"enabled_no_permission_ban,omitempty"`
	WarnErrorRate          *float64           `json:"warn_error_rate,omitempty"`
	MaxErrorRate           *float64           `json:"max_error_rate,omitempty"`
}

GroupChannelPatch keeps omitted fields unchanged while allowing explicit zero values to be persisted during group channel updates.

type GroupChannelRequestDetail

type GroupChannelRequestDetail struct {
	CreatedAt             time.Time `gorm:"autoCreateTime;index" json:"-"`
	RequestBody           string    `gorm:"type:text"            json:"request_body,omitempty"`
	ResponseBody          string    `gorm:"type:text"            json:"response_body,omitempty"`
	RequestBodyTruncated  bool      `                            json:"request_body_truncated,omitempty"`
	ResponseBodyTruncated bool      `                            json:"response_body_truncated,omitempty"`
	ID                    int       `gorm:"primaryKey"           json:"id"`
	LogID                 int       `gorm:"index"                json:"log_id"`
}

type GroupChannelRetryLog

type GroupChannelRetryLog struct {
	RequestBody           string          `gorm:"type:text"                                         json:"request_body,omitempty"`
	ResponseBody          string          `gorm:"type:text"                                         json:"response_body,omitempty"`
	RequestBodyTruncated  bool            `                                                         json:"request_body_truncated,omitempty"`
	ResponseBodyTruncated bool            `                                                         json:"response_body_truncated,omitempty"`
	RequestAt             time.Time       `                                                         json:"request_at"`
	RetryAt               time.Time       `                                                         json:"retry_at,omitempty"`
	TTFBMilliseconds      ZeroNullInt64   `                                                         json:"ttfb_milliseconds,omitempty"`
	CreatedAt             time.Time       `gorm:"autoCreateTime;index"                              json:"created_at"`
	GroupID               string          `gorm:"size:64;index"                                     json:"group,omitempty"`
	Model                 string          `gorm:"size:128"                                          json:"model"`
	RequestID             EmptyNullString `gorm:"type:char(16);index:,where:request_id is not null" json:"request_id"`
	ID                    int             `gorm:"primaryKey"                                        json:"id"`
	GroupChannelID        int             `                                                         json:"group_channel_id,omitempty"`
	Code                  int             `gorm:"index"                                             json:"code,omitempty"`
	Mode                  int             `                                                         json:"mode,omitempty"`
	RetryTimes            ZeroNullInt64   `                                                         json:"retry_times,omitempty"`
}

type GroupChannelStoreV2

type GroupChannelStoreV2 struct {
	ID        string    `gorm:"size:128;primaryKey:3"`
	CreatedAt time.Time `gorm:"autoCreateTime"`
	UpdatedAt time.Time `gorm:"autoUpdateTime"`
	ExpiresAt time.Time `gorm:"index"`
	GroupID   string    `gorm:"size:64;primaryKey:1"`
	TokenID   int       `gorm:"primaryKey:2"`
	ChannelID int
	Model     string `gorm:"size:128"`
	Metadata  string `gorm:"type:text"`
}

func (*GroupChannelStoreV2) BeforeSave

func (s *GroupChannelStoreV2) BeforeSave(_ *gorm.DB) error

type GroupChannelSummary

type GroupChannelSummary struct {
	ID     int                       `gorm:"primaryKey"`
	Unique GroupChannelSummaryUnique `gorm:"embedded"`
	Data   SummaryData               `gorm:"embedded"`
}

func (*GroupChannelSummary) BeforeCreate

func (l *GroupChannelSummary) BeforeCreate(_ *gorm.DB) error

type GroupChannelSummaryMinute

type GroupChannelSummaryMinute struct {
	ID     int                             `gorm:"primaryKey"`
	Unique GroupChannelSummaryMinuteUnique `gorm:"embedded"`
	Data   SummaryData                     `gorm:"embedded"`
}

func (*GroupChannelSummaryMinute) BeforeCreate

func (l *GroupChannelSummaryMinute) BeforeCreate(_ *gorm.DB) error

type GroupChannelSummaryMinuteUnique

type GroupChannelSummaryMinuteUnique struct {
	GroupID         string `gorm:"size:64;not null;uniqueIndex:idx_group_channel_summary_minute_unique,priority:1"`
	GroupChannelID  int    `gorm:"not null;uniqueIndex:idx_group_channel_summary_minute_unique,priority:2"`
	Model           string `gorm:"size:128;not null;uniqueIndex:idx_group_channel_summary_minute_unique,priority:3"`
	MinuteTimestamp int64  `gorm:"not null;uniqueIndex:idx_group_channel_summary_minute_unique,priority:4,sort:desc"`
}

type GroupChannelSummaryMinuteUpdate

type GroupChannelSummaryMinuteUpdate struct {
	GroupChannelSummaryMinuteUnique
	SummaryData
}

type GroupChannelSummaryUnique

type GroupChannelSummaryUnique struct {
	GroupID        string `gorm:"size:64;not null;uniqueIndex:idx_group_channel_summary_unique,priority:1"`
	GroupChannelID int    `gorm:"not null;uniqueIndex:idx_group_channel_summary_unique,priority:2"`
	Model          string `gorm:"size:128;not null;uniqueIndex:idx_group_channel_summary_unique,priority:3"`
	HourTimestamp  int64  `gorm:"not null;uniqueIndex:idx_group_channel_summary_unique,priority:4,sort:desc"`
}

type GroupChannelSummaryUpdate

type GroupChannelSummaryUpdate struct {
	GroupChannelSummaryUnique
	SummaryData
}

type GroupChannelTest

type GroupChannelTest struct {
	TestAt         time.Time   `json:"test_at"`
	Model          string      `json:"model"            gorm:"size:128;primaryKey"`
	ActualModel    string      `json:"actual_model"     gorm:"size:128"`
	Response       string      `json:"response"         gorm:"type:text"`
	GroupID        string      `json:"group_id"         gorm:"size:64;primaryKey"`
	ChannelName    string      `json:"channel_name"     gorm:"size:64"`
	ChannelType    ChannelType `json:"channel_type"`
	GroupChannelID int         `json:"group_channel_id" gorm:"primaryKey"`
	Took           float64     `json:"took"`
	Success        bool        `json:"success"`
	Mode           mode.Mode   `json:"mode"`
	Code           int         `json:"code"`
}

func GetGroupChannelTests

func GetGroupChannelTests(group string, id int) ([]*GroupChannelTest, error)

func (*GroupChannelTest) MarshalJSON

func (ct *GroupChannelTest) MarshalJSON() ([]byte, error)

type GroupChannelTokenSummary

type GroupChannelTokenSummary struct {
	ID     int                            `gorm:"primaryKey"`
	Unique GroupChannelTokenSummaryUnique `gorm:"embedded"`
	Data   SummaryData                    `gorm:"embedded"`
}

func (*GroupChannelTokenSummary) BeforeCreate

func (l *GroupChannelTokenSummary) BeforeCreate(_ *gorm.DB) error

type GroupChannelTokenSummaryMinute

type GroupChannelTokenSummaryMinute struct {
	ID     int                                  `gorm:"primaryKey"`
	Unique GroupChannelTokenSummaryMinuteUnique `gorm:"embedded"`
	Data   SummaryData                          `gorm:"embedded"`
}

func (*GroupChannelTokenSummaryMinute) BeforeCreate

func (l *GroupChannelTokenSummaryMinute) BeforeCreate(_ *gorm.DB) error

type GroupChannelTokenSummaryMinuteUnique

type GroupChannelTokenSummaryMinuteUnique struct {
	GroupID         string `gorm:"size:64;not null;uniqueIndex:idx_group_channel_token_summary_minute_unique,priority:1"`
	TokenName       string `gorm:"size:32;not null;uniqueIndex:idx_group_channel_token_summary_minute_unique,priority:2"`
	Model           string `gorm:"size:128;not null;uniqueIndex:idx_group_channel_token_summary_minute_unique,priority:3"`
	MinuteTimestamp int64  `gorm:"not null;uniqueIndex:idx_group_channel_token_summary_minute_unique,priority:4,sort:desc"`
}

type GroupChannelTokenSummaryMinuteUpdate

type GroupChannelTokenSummaryMinuteUpdate struct {
	GroupChannelTokenSummaryMinuteUnique
	SummaryData
}

type GroupChannelTokenSummaryUnique

type GroupChannelTokenSummaryUnique struct {
	GroupID       string `gorm:"size:64;not null;uniqueIndex:idx_group_channel_token_summary_unique,priority:1"`
	TokenName     string `gorm:"size:32;not null;uniqueIndex:idx_group_channel_token_summary_unique,priority:2"`
	Model         string `gorm:"size:128;not null;uniqueIndex:idx_group_channel_token_summary_unique,priority:3"`
	HourTimestamp int64  `gorm:"not null;uniqueIndex:idx_group_channel_token_summary_unique,priority:4,sort:desc"`
}

type GroupChannelTokenSummaryUpdate

type GroupChannelTokenSummaryUpdate struct {
	GroupChannelTokenSummaryUnique
	SummaryData
}

type GroupChannelsCache

type GroupChannelsCache struct {
	GroupID  string          `json:"group_id" redis:"g"`
	Channels []*GroupChannel `json:"channels" redis:"c"`
}

func CacheGetGroupChannels

func CacheGetGroupChannels(group string) (*GroupChannelsCache, error)

type GroupConsumptionRankingItem

type GroupConsumptionRankingItem struct {
	GroupID      string  `json:"group_id"      gorm:"column:group_id"`
	RequestCount int64   `json:"request_count" gorm:"column:request_count"`
	UsedAmount   float64 `json:"used_amount"   gorm:"column:used_amount"`
	InputTokens  int64   `json:"input_tokens"  gorm:"column:input_tokens"`
	OutputTokens int64   `json:"output_tokens" gorm:"column:output_tokens"`
	TotalTokens  int64   `json:"total_tokens"  gorm:"column:total_tokens"`
}

func GetGroupConsumptionRanking

func GetGroupConsumptionRanking(
	start, end time.Time,
	page, perPage int,
	order string,
) ([]GroupConsumptionRankingItem, int64, string, error)

type GroupDashboardResponse

type GroupDashboardResponse struct {
	DashboardResponse
	TokenNames []string `json:"token_names"`
}

func GetGlobalGroupChannelTokenDashboardData

func GetGlobalGroupChannelTokenDashboardData(
	group string,
	start, end time.Time,
	tokenName string,
	modelName string,
	timeSpan TimeSpanType,
	timezone *time.Location,
	fields SummarySelectFields,
) (*GroupDashboardResponse, error)

func GetGroupChannelTokenDashboardData

func GetGroupChannelTokenDashboardData(
	group string,
	start, end time.Time,
	tokenName string,
	modelName string,
	timeSpan TimeSpanType,
	timezone *time.Location,
	fields SummarySelectFields,
) (*GroupDashboardResponse, error)

func GetGroupDashboardData

func GetGroupDashboardData(
	group string,
	start, end time.Time,
	tokenName string,
	modelName string,
	timeSpan TimeSpanType,
	timezone *time.Location,
	fields SummarySelectFields,
) (*GroupDashboardResponse, error)

type GroupDashboardV2Response

type GroupDashboardV2Response struct {
	DashboardV2Response
	TokenNames []string `json:"token_names"`
}

func GetGlobalGroupChannelTokenDashboardV2Data

func GetGlobalGroupChannelTokenDashboardV2Data(
	group string,
	tokenName string,
	modelName string,
	start, end time.Time,
	timeSpan TimeSpanType,
	timezone *time.Location,
	fields SummarySelectFields,
) (*GroupDashboardV2Response, error)

func GetGroupChannelTokenDashboardV2Data

func GetGroupChannelTokenDashboardV2Data(
	group string,
	tokenName string,
	modelName string,
	start, end time.Time,
	timeSpan TimeSpanType,
	timezone *time.Location,
	fields SummarySelectFields,
) (*GroupDashboardV2Response, error)

func GetGroupDashboardV2Data

func GetGroupDashboardV2Data(
	group string,
	tokenName string,
	modelName string,
	start, end time.Time,
	timeSpan TimeSpanType,
	timezone *time.Location,
	fields SummarySelectFields,
) (*GroupDashboardV2Response, error)

type GroupDashboardV3Response

type GroupDashboardV3Response = GroupDashboardV2Response

func GetGlobalGroupChannelTokenDashboardV3Data

func GetGlobalGroupChannelTokenDashboardV3Data(
	group string,
	tokenName string,
	modelName string,
	start, end time.Time,
	timeSpan TimeSpanType,
	timezone *time.Location,
	fields SummarySelectFields,
) (*GroupDashboardV3Response, error)

func GetGroupChannelTokenDashboardV3Data

func GetGroupChannelTokenDashboardV3Data(
	group string,
	tokenName string,
	modelName string,
	start, end time.Time,
	timeSpan TimeSpanType,
	timezone *time.Location,
	fields SummarySelectFields,
) (*GroupDashboardV3Response, error)

func GetGroupDashboardV3Data

func GetGroupDashboardV3Data(
	group string,
	tokenName string,
	modelName string,
	start, end time.Time,
	timeSpan TimeSpanType,
	timezone *time.Location,
	fields SummarySelectFields,
) (*GroupDashboardV3Response, error)

type GroupMCP

type GroupMCP struct {
	ID            string               `gorm:"primaryKey"                    json:"id"`
	GroupID       string               `gorm:"primaryKey"                    json:"group_id"`
	Group         *Group               `gorm:"foreignKey:GroupID"            json:"-"`
	Status        GroupMCPStatus       `gorm:"index;default:1"               json:"status"`
	CreatedAt     time.Time            `gorm:"index,autoCreateTime"          json:"created_at"`
	UpdateAt      time.Time            `gorm:"index,autoUpdateTime"          json:"update_at"`
	Name          string               `                                     json:"name"`
	Type          GroupMCPType         `gorm:"index"                         json:"type"`
	Description   string               `                                     json:"description"`
	ProxyConfig   *GroupMCPProxyConfig `gorm:"serializer:fastjson;type:text" json:"proxy_config,omitempty"`
	OpenAPIConfig *MCPOpenAPIConfig    `gorm:"serializer:fastjson;type:text" json:"openapi_config,omitempty"`
}

func GetAllGroupMCPs

func GetAllGroupMCPs(status GroupMCPStatus) ([]GroupMCP, error)

func GetGroupMCPByID

func GetGroupMCPByID(id, groupID string) (GroupMCP, error)

GetGroupMCPByID retrieves a GroupMCP by ID and GroupID

func GetGroupMCPs

func GetGroupMCPs(
	groupID string,
	page, perPage int,
	id string,
	mcpType GroupMCPType,
	keyword string,
	status GroupMCPStatus,
) (mcps []GroupMCP, total int64, err error)

GetGroupMCPs retrieves GroupMCPs with pagination and filtering

func (*GroupMCP) BeforeSave

func (g *GroupMCP) BeforeSave(_ *gorm.DB) (err error)

func (*GroupMCP) ToGroupMCPCache

func (g *GroupMCP) ToGroupMCPCache() *GroupMCPCache

type GroupMCPCache

type GroupMCPCache struct {
	ID            string               `json:"id"             redis:"i"`
	GroupID       string               `json:"group_id"       redis:"g"`
	Status        GroupMCPStatus       `json:"status"         redis:"s"`
	Type          GroupMCPType         `json:"type"           redis:"t"`
	ProxyConfig   *GroupMCPProxyConfig `json:"proxy_config"   redis:"pc"`
	OpenAPIConfig *MCPOpenAPIConfig    `json:"openapi_config" redis:"oc"`
}

func CacheGetGroupMCP

func CacheGetGroupMCP(groupID, mcpID string) (*GroupMCPCache, error)

type GroupMCPProxyConfig

type GroupMCPProxyConfig struct {
	URL     string            `json:"url"`
	Querys  map[string]string `json:"querys"`
	Headers map[string]string `json:"headers"`
}

func (*GroupMCPProxyConfig) MarshalBinary

func (c *GroupMCPProxyConfig) MarshalBinary() ([]byte, error)

func (*GroupMCPProxyConfig) ScanRedis

func (c *GroupMCPProxyConfig) ScanRedis(value string) error

type GroupMCPStatus

type GroupMCPStatus int
const (
	GroupMCPStatusEnabled GroupMCPStatus = iota + 1
	GroupMCPStatusDisabled
)

func (GroupMCPStatus) MarshalBinary

func (s GroupMCPStatus) MarshalBinary() ([]byte, error)

func (*GroupMCPStatus) ScanRedis

func (s *GroupMCPStatus) ScanRedis(value string) error

type GroupMCPType

type GroupMCPType string
const (
	GroupMCPTypeProxySSE        GroupMCPType = "mcp_proxy_sse"
	GroupMCPTypeProxyStreamable GroupMCPType = "mcp_proxy_streamable"
	GroupMCPTypeOpenAPI         GroupMCPType = "mcp_openapi"
)

func (GroupMCPType) MarshalBinary

func (t GroupMCPType) MarshalBinary() ([]byte, error)

func (*GroupMCPType) ScanRedis

func (t *GroupMCPType) ScanRedis(value string) error

type GroupModelConfig

type GroupModelConfig struct {
	GroupID string `gorm:"primaryKey"         json:"group_id"`
	Group   *Group `gorm:"foreignKey:GroupID" json:"-"`
	Model   string `gorm:"primaryKey"         json:"model"`

	OverrideLimit bool  `json:"override_limit"`
	RPM           int64 `json:"rpm"`
	TPM           int64 `json:"tpm"`

	OverridePrice bool  `json:"override_price"`
	Price         Price `json:"price,omitempty" gorm:"embedded"`

	OverrideRetryTimes bool  `json:"override_retry_times"`
	RetryTimes         int64 `json:"retry_times"`

	OverrideRetryBudget bool  `json:"override_retry_budget"`
	RetryBudget         int64 `json:"retry_budget"          binding:"gte=0,lte=180" minimum:"0" maximum:"180"`

	OverrideTimeoutConfig bool          `json:"override_timeout_config"`
	TimeoutConfig         TimeoutConfig `json:"timeout_config,omitempty" gorm:"embedded"`

	OverrideForceSaveDetail bool `json:"override_force_save_detail"`
	ForceSaveDetail         bool `json:"force_save_detail"`

	OverrideMaxImageGenerationCount bool `json:"override_max_image_generation_count"`
	MaxImageGenerationCount         int  `json:"max_image_generation_count"`

	OverrideMaxVideoGenerationSeconds bool `json:"override_max_video_generation_seconds"`
	MaxVideoGenerationSeconds         int  `json:"max_video_generation_seconds"`

	OverrideMaxVideoGenerationCount bool `json:"override_max_video_generation_count"`
	MaxVideoGenerationCount         int  `json:"max_video_generation_count"`

	OverrideRequestBodyStorageMaxSize bool  `json:"override_request_body_storage_max_size"`
	RequestBodyStorageMaxSize         int64 `json:"request_body_storage_max_size"`

	OverrideResponseBodyStorageMaxSize bool  `json:"override_response_body_storage_max_size"`
	ResponseBodyStorageMaxSize         int64 `json:"response_body_storage_max_size"`

	OverrideSummaryServiceTier bool `json:"override_summary_service_tier"`
	SummaryServiceTier         bool `json:"summary_service_tier"`

	OverrideSummaryClaudeLongContext bool `json:"override_summary_claude_long_context"`
	SummaryClaudeLongContext         bool `json:"summary_claude_long_context"`
}

func GetGroupModelConfig

func GetGroupModelConfig(groupID, model string) (*GroupModelConfig, error)

func GetGroupModelConfigs

func GetGroupModelConfigs(groupID string) ([]GroupModelConfig, error)

func (*GroupModelConfig) BeforeSave

func (g *GroupModelConfig) BeforeSave(_ *gorm.DB) (err error)

type GroupScopeModelConfig

type GroupScopeModelConfig struct {
	ModelConfig
	GroupID string `gorm:"size:64;primaryKey" json:"group_id" yaml:"group_id,omitempty"`
	Group   *Group `gorm:"foreignKey:GroupID" json:"-"        yaml:"-"`
}

func GetAllGroupScopeModelConfigs

func GetAllGroupScopeModelConfigs(group string) ([]GroupScopeModelConfig, error)

func GetGroupScopeModelConfig

func GetGroupScopeModelConfig(group, modelName string) (GroupScopeModelConfig, error)

func GetGroupScopeModelConfigs

func GetGroupScopeModelConfigs(
	group string,
	page, perPage int,
	modelName string,
) (configs []GroupScopeModelConfig, total int64, err error)

func GetGroupScopeModelConfigsByModels

func GetGroupScopeModelConfigsByModels(
	group string,
	models []string,
) ([]GroupScopeModelConfig, error)

func SearchGroupScopeModelConfigs

func SearchGroupScopeModelConfigs(
	group, keyword, modelName string,
	page, perPage int,
	owner ModelOwner,
) (configs []GroupScopeModelConfig, total int64, err error)

func (*GroupScopeModelConfig) BeforeSave

func (c *GroupScopeModelConfig) BeforeSave(_ *gorm.DB) error

func (*GroupScopeModelConfig) ToModelConfig

func (c *GroupScopeModelConfig) ToModelConfig() ModelConfig

type GroupScopeModelConfigsCache

type GroupScopeModelConfigsCache struct {
	GroupID string                  `json:"group_id" redis:"g"`
	Models  []string                `json:"models"   redis:"m"`
	Configs map[string]ModelConfig  `json:"configs"  redis:"c"`
	List    []GroupScopeModelConfig `json:"list"     redis:"l"`
}

func CacheGetGroupScopeModelConfigs

func CacheGetGroupScopeModelConfigs(group string) (*GroupScopeModelConfigsCache, error)

type GroupSummary

type GroupSummary struct {
	ID     int                `gorm:"primaryKey"`
	Unique GroupSummaryUnique `gorm:"embedded"`
	Data   SummaryData        `gorm:"embedded"`
}

only summary result only requests

func (*GroupSummary) BeforeCreate

func (l *GroupSummary) BeforeCreate(_ *gorm.DB) (err error)

type GroupSummaryMinute

type GroupSummaryMinute struct {
	ID     int                      `gorm:"primaryKey"`
	Unique GroupSummaryMinuteUnique `gorm:"embedded"`
	Data   SummaryData              `gorm:"embedded"`
}

only summary result only requests

func (*GroupSummaryMinute) BeforeCreate

func (l *GroupSummaryMinute) BeforeCreate(_ *gorm.DB) (err error)

type GroupSummaryMinuteUnique

type GroupSummaryMinuteUnique struct {
	GroupID         string `gorm:"size:64;not null;uniqueIndex:idx_groupsummary_minute_unique,priority:1"`
	TokenName       string `gorm:"size:32;not null;uniqueIndex:idx_groupsummary_minute_unique,priority:2"`
	Model           string `gorm:"size:128;not null;uniqueIndex:idx_groupsummary_minute_unique,priority:3"`
	MinuteTimestamp int64  `gorm:"not null;uniqueIndex:idx_groupsummary_minute_unique,priority:4,sort:desc"`
}

type GroupSummaryMinuteUpdate

type GroupSummaryMinuteUpdate struct {
	GroupSummaryMinuteUnique
	SummaryData
}

type GroupSummaryUnique

type GroupSummaryUnique struct {
	GroupID       string `gorm:"size:64;not null;uniqueIndex:idx_groupsummary_unique,priority:1"`
	TokenName     string `gorm:"size:32;not null;uniqueIndex:idx_groupsummary_unique,priority:2"`
	Model         string `gorm:"size:128;not null;uniqueIndex:idx_groupsummary_unique,priority:3"`
	HourTimestamp int64  `gorm:"not null;uniqueIndex:idx_groupsummary_unique,priority:4,sort:desc"`
}

type GroupSummaryUpdate

type GroupSummaryUpdate struct {
	GroupSummaryUnique
	SummaryData
}

type GroupUpdate

type GroupUpdate struct {
	Amount decimal.Decimal
	Count  int
}

type GroupUsageAlertItem

type GroupUsageAlertItem struct {
	GroupID           string
	ThreeDayAvgAmount float64 // 前三天的平均用量
	TodayAmount       float64
	Ratio             float64
}

GroupUsageAlertItem 用量告警项

func GetGroupUsageAlert

func GetGroupUsageAlert(
	threshold, minAvgThreshold float64,
	whitelist []string,
) ([]GroupUsageAlertItem, error)

GetGroupUsageAlert 获取用量突升异常的用户 新的检测逻辑: 1. 基准阈值:当天用量必须 >= threshold(如 100)才开始检测 2. 动态倍率:根据前三天平均用量分段计算告警倍率

  • 前三天平均用量 < 100:倍率 5.0(小用户突增 5 倍很异常)
  • 前三天平均用量 [100, 300):倍率 4.0
  • 前三天平均用量 [300, 1000):倍率 3.0
  • 前三天平均用量 [1000, 2000):倍率 2.5
  • 前三天平均用量 [2000, 5000):倍率 2.0
  • 前三天平均用量 >= 5000:倍率 1.5(大用户增长 1.5 倍就值得关注)

3. 前三天平均用量必须 >= minAvgThreshold(如 3)才进行检测 4. 不在白名单中

type Log

type Log struct {
	RequestDetail    *RequestDetail   `gorm:"foreignKey:LogID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;" json:"request_detail,omitempty"`
	RequestAt        time.Time        `                                                                      json:"request_at"`
	RetryAt          time.Time        `                                                                      json:"retry_at,omitempty"`
	TTFBMilliseconds ZeroNullInt64    `                                                                      json:"ttfb_milliseconds,omitempty"`
	CreatedAt        time.Time        `gorm:"autoCreateTime;index"                                           json:"created_at"`
	TokenName        string           `gorm:"size:32"                                                        json:"token_name,omitempty"`
	Endpoint         EmptyNullString  `gorm:"size:64"                                                        json:"endpoint,omitempty"`
	Content          EmptyNullString  `gorm:"type:text"                                                      json:"content,omitempty"`
	GroupID          string           `gorm:"size:64"                                                        json:"group,omitempty"`
	Model            string           `gorm:"size:128"                                                       json:"model"`
	RequestID        EmptyNullString  `gorm:"type:char(16);index:,where:request_id is not null"              json:"request_id"`
	UpstreamID       EmptyNullString  `gorm:"type:varchar(256)"                                              json:"upstream_id,omitempty"`
	AsyncUsageStatus AsyncUsageStatus `                                                                      json:"async_usage_status,omitempty"`
	ID               int              `gorm:"primaryKey"                                                     json:"id"`
	TokenID          int              `gorm:"index"                                                          json:"token_id,omitempty"`
	ChannelID        int              `                                                                      json:"channel,omitempty"`
	Code             int              `gorm:"index"                                                          json:"code,omitempty"`
	Mode             int              `                                                                      json:"mode,omitempty"`
	IP               EmptyNullString  `gorm:"size:45;index:,where:ip is not null"                            json:"ip,omitempty"`
	RetryTimes       ZeroNullInt64    `                                                                      json:"retry_times,omitempty"`
	Price            Price            `gorm:"embedded"                                                       json:"price,omitempty"`
	Usage            Usage            `gorm:"embedded"                                                       json:"usage,omitempty"`
	UsageContext     UsageContext     `gorm:"embedded"                                                       json:"usage_context,omitempty"`
	Amount           Amount           `gorm:"embedded"                                                       json:"amount,omitempty"`
	PromptCacheKey   EmptyNullString  `gorm:"type:text"                                                      json:"prompt_cache_key,omitempty"`
	// https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids
	User     EmptyNullString   `gorm:"type:text"                     json:"user,omitempty"`
	Metadata map[string]string `gorm:"serializer:fastjson;type:text" json:"metadata,omitempty"`
}

func ExportGroupLogs

func ExportGroupLogs(
	group string,
	startTimestamp time.Time,
	endTimestamp time.Time,
	modelName string,
	requestID string,
	upstreamID string,
	tokenID int,
	tokenName string,
	channelID int,
	order string,
	codeType CodeType,
	code int,
	withBody bool,
	ip string,
	user string,
	maxEntries int,
) ([]*Log, error)

func ExportGroupLogsRange

func ExportGroupLogsRange(
	group string,
	startTimestamp time.Time,
	endExclusive time.Time,
	modelName string,
	requestID string,
	upstreamID string,
	tokenID int,
	tokenName string,
	channelID int,
	order string,
	codeType CodeType,
	code int,
	withBody bool,
	ip string,
	user string,
	maxEntries int,
) ([]*Log, error)

func ExportLogs

func ExportLogs(
	startTimestamp time.Time,
	endTimestamp time.Time,
	modelName string,
	requestID string,
	upstreamID string,
	channelID int,
	order string,
	codeType CodeType,
	code int,
	withBody bool,
	ip string,
	user string,
	maxEntries int,
) ([]*Log, error)

func ExportLogsRange

func ExportLogsRange(
	startTimestamp time.Time,
	endExclusive time.Time,
	modelName string,
	requestID string,
	upstreamID string,
	channelID int,
	order string,
	codeType CodeType,
	code int,
	withBody bool,
	ip string,
	user string,
	maxEntries int,
) ([]*Log, error)

func (*Log) BeforeCreate

func (l *Log) BeforeCreate(_ *gorm.DB) (err error)

func (*Log) MarshalJSON

func (l *Log) MarshalJSON() ([]byte, error)

type MCPEmbeddingConfig

type MCPEmbeddingConfig struct {
	Init    map[string]string       `json:"init"`
	Reusing map[string]ReusingParam `json:"reusing"`
}

func (*MCPEmbeddingConfig) MarshalBinary

func (c *MCPEmbeddingConfig) MarshalBinary() ([]byte, error)

func (*MCPEmbeddingConfig) ScanRedis

func (c *MCPEmbeddingConfig) ScanRedis(value string) error

type MCPOpenAPIConfig

type MCPOpenAPIConfig struct {
	OpenAPISpec    string `json:"openapi_spec"`
	OpenAPIContent string `json:"openapi_content,omitempty"`
	V2             bool   `json:"v2"`
	ServerAddr     string `json:"server_addr,omitempty"`
	Authorization  string `json:"authorization,omitempty"`
}

func (*MCPOpenAPIConfig) MarshalBinary

func (c *MCPOpenAPIConfig) MarshalBinary() ([]byte, error)

func (*MCPOpenAPIConfig) ScanRedis

func (c *MCPOpenAPIConfig) ScanRedis(value string) error

type MCPPrice

type MCPPrice struct {
	DefaultToolsCallPrice float64            `json:"default_tools_call_price"`
	ToolsCallPrices       map[string]float64 `json:"tools_call_prices"        gorm:"serializer:fastjson;type:text"`
}

func (MCPPrice) MarshalBinary

func (p MCPPrice) MarshalBinary() ([]byte, error)

func (*MCPPrice) ScanRedis

func (p *MCPPrice) ScanRedis(value string) error

type ModelCaches

type ModelCaches struct {
	ChannelsByID map[int]*Channel

	ModelConfig ModelConfigCache

	EnabledModelsBySet       map[string][]string
	EnabledModelConfigsBySet map[string][]ModelConfig
	EnabledModelConfigsMap   map[string]ModelConfig

	EnabledModel2ChannelsBySet  map[string]map[string][]*Channel
	DisabledModel2ChannelsBySet map[string]map[string][]*Channel
}

func LoadModelCaches

func LoadModelCaches() *ModelCaches

type ModelConfig

type ModelConfig struct {
	CreatedAt        time.Time                 `gorm:"index;autoCreateTime"          json:"created_at"                               yaml:"-"`
	UpdatedAt        time.Time                 `gorm:"index;autoUpdateTime"          json:"updated_at"                               yaml:"-"`
	Config           map[ModelConfigKey]any    `gorm:"serializer:fastjson;type:text" json:"config,omitempty"                         yaml:"config,omitempty"`
	Plugin           map[string]map[string]any `gorm:"serializer:fastjson;type:text" json:"plugin,omitempty"                         yaml:"plugin,omitempty"`
	Model            string                    `gorm:"size:128;primaryKey"           json:"model"                                    yaml:"model,omitempty"`
	Owner            ModelOwner                `gorm:"type:varchar(32);index"        json:"owner"                                    yaml:"owner,omitempty"`
	Type             mode.Mode                 `                                     json:"type"                                     yaml:"type,omitempty"`
	ExcludeFromTests bool                      `                                     json:"exclude_from_tests,omitempty"             yaml:"exclude_from_tests,omitempty"`
	RPM              int64                     `                                     json:"rpm,omitempty"                            yaml:"rpm,omitempty"`
	TPM              int64                     `                                     json:"tpm,omitempty"                            yaml:"tpm,omitempty"`
	Price            Price                     `gorm:"embedded"                      json:"price,omitempty"                          yaml:"price,omitempty"`
	RetryTimes       int64                     `                                     json:"retry_times,omitempty"                    yaml:"retry_times,omitempty"`
	RetryBudget      *int64                    `` // Seconds; nil inherits the global budget, zero disables it.
	/* 192-byte string literal not displayed */
	TimeoutConfig               TimeoutConfig `gorm:"embedded"                      json:"timeout_config,omitempty"                 yaml:"timeout_config,omitempty"`
	ForceSaveDetail             bool          `                                     json:"force_save_detail,omitempty"              yaml:"force_save_detail,omitempty"`
	MaxImageGenerationCount     int           `` /* 128-byte string literal not displayed */
	MaxVideoGenerationSeconds   int           `` /* 130-byte string literal not displayed */
	MaxVideoGenerationCount     int           `` /* 128-byte string literal not displayed */
	AllowedResolutions          []string      `gorm:"serializer:fastjson;type:text" json:"allowed_resolutions,omitempty"            yaml:"allowed_resolutions,omitempty"`
	RequestBodyStorageMaxSize   int64         `` /* 131-byte string literal not displayed */
	ResponseBodyStorageMaxSize  int64         `` /* 132-byte string literal not displayed */
	SummaryServiceTier          bool          `                                     json:"summary_service_tier,omitempty"           yaml:"summary_service_tier,omitempty"`
	SummaryClaudeLongContext    bool          `` /* 129-byte string literal not displayed */
	DisableResolutionFuzzyMatch bool          `` /* 132-byte string literal not displayed */
	// contains filtered or unexported fields
}

func CacheGetGroupScopeModelConfig

func CacheGetGroupScopeModelConfig(group, modelName string) (ModelConfig, bool)

func GetAllModelConfigs

func GetAllModelConfigs() (configs []ModelConfig, err error)

func GetModelConfig

func GetModelConfig(model string) (ModelConfig, error)

func GetModelConfigs

func GetModelConfigs(
	page, perPage int,
	model string,
) (configs []*ModelConfig, total int64, err error)

func GetModelConfigsByModels

func GetModelConfigsByModels(models []string) (configs []ModelConfig, err error)

func NewDefaultModelConfig

func NewDefaultModelConfig(model string) ModelConfig

func ResolveGroupScopeModelConfig

func ResolveGroupScopeModelConfig(group, modelName string) (ModelConfig, bool)

func SearchModelConfigs

func SearchModelConfigs(
	keyword string,
	page, perPage int,
	model string,
	owner ModelOwner,
) (configs []ModelConfig, total int64, err error)

func (*ModelConfig) BeforeSave

func (c *ModelConfig) BeforeSave(_ *gorm.DB) (err error)

func (*ModelConfig) LoadFromGroupModelConfig

func (c *ModelConfig) LoadFromGroupModelConfig(groupModelConfig GroupModelConfig) ModelConfig

func (*ModelConfig) LoadPluginConfig

func (c *ModelConfig) LoadPluginConfig(pluginName string, config any) error

func (*ModelConfig) MarshalJSON

func (c *ModelConfig) MarshalJSON() ([]byte, error)

func (*ModelConfig) MaxContextTokens

func (c *ModelConfig) MaxContextTokens() (int, bool)

func (*ModelConfig) MaxInputTokens

func (c *ModelConfig) MaxInputTokens() (int, bool)

func (*ModelConfig) MaxOutputTokens

func (c *ModelConfig) MaxOutputTokens() (int, bool)

func (*ModelConfig) RequestTimeout

func (c *ModelConfig) RequestTimeout() time.Duration

func (*ModelConfig) RetryLimits

func (c *ModelConfig) RetryLimits(defaultTimes, defaultBudget int64) (int64, time.Duration)

func (*ModelConfig) ShouldSummaryClaudeLongContext

func (c *ModelConfig) ShouldSummaryClaudeLongContext() bool

func (*ModelConfig) ShouldSummaryServiceTier

func (c *ModelConfig) ShouldSummaryServiceTier() bool

func (*ModelConfig) StreamRequestTimeout

func (c *ModelConfig) StreamRequestTimeout() time.Duration

func (*ModelConfig) SupportFormats

func (c *ModelConfig) SupportFormats() ([]string, bool)

func (*ModelConfig) SupportStreamTimeout

func (c *ModelConfig) SupportStreamTimeout() bool

func (*ModelConfig) SupportToolChoice

func (c *ModelConfig) SupportToolChoice() (bool, bool)

func (*ModelConfig) SupportVision

func (c *ModelConfig) SupportVision() (bool, bool)

func (*ModelConfig) SupportVoices

func (c *ModelConfig) SupportVoices() ([]string, bool)

type ModelConfigCache

type ModelConfigCache interface {
	GetModelConfig(model string) (ModelConfig, bool)
}

type ModelConfigItem

type ModelConfigItem struct {
	ModelConfig `       yaml:",inline"` // Embed ModelConfig to inherit all fields
	TypeName    string                  `yaml:"type_name,omitempty"` // Alternative to Type (e.g., "chat", "embedding")
}

ModelConfigItem wraps ModelConfig for YAML configuration Adds TypeName field for human-readable model type specification

func (*ModelConfigItem) GetModelType

func (m *ModelConfigItem) GetModelType() mode.Mode

GetModelType returns the model type, converting from TypeName if Type is not set

type ModelConfigKey

type ModelConfigKey string
const (
	ModelConfigMaxContextTokensKey ModelConfigKey = "max_context_tokens"
	ModelConfigMaxInputTokensKey   ModelConfigKey = "max_input_tokens"
	ModelConfigMaxOutputTokensKey  ModelConfigKey = "max_output_tokens"
	ModelConfigVisionKey           ModelConfigKey = "vision"
	ModelConfigToolChoiceKey       ModelConfigKey = "tool_choice"
	ModelConfigSupportFormatsKey   ModelConfigKey = "support_formats"
	ModelConfigSupportVoicesKey    ModelConfigKey = "support_voices"
)

type ModelConfigOption

type ModelConfigOption func(config map[ModelConfigKey]any)

func WithModelConfigMaxContextTokens

func WithModelConfigMaxContextTokens(maxContextTokens int) ModelConfigOption

func WithModelConfigMaxInputTokens

func WithModelConfigMaxInputTokens(maxInputTokens int) ModelConfigOption

func WithModelConfigMaxOutputTokens

func WithModelConfigMaxOutputTokens(maxOutputTokens int) ModelConfigOption

func WithModelConfigSupportFormats

func WithModelConfigSupportFormats(supportFormats []string) ModelConfigOption

func WithModelConfigSupportVoices

func WithModelConfigSupportVoices(supportVoices []string) ModelConfigOption

func WithModelConfigToolChoice

func WithModelConfigToolChoice(toolChoice bool) ModelConfigOption

func WithModelConfigVision

func WithModelConfigVision(vision bool) ModelConfigOption

type ModelOwner

type ModelOwner string
const (
	ModelOwnerOpenAI      ModelOwner = "openai"
	ModelOwnerAlibaba     ModelOwner = "alibaba"
	ModelOwnerTencent     ModelOwner = "tencent"
	ModelOwnerXunfei      ModelOwner = "xunfei"
	ModelOwnerDeepSeek    ModelOwner = "deepseek"
	ModelOwnerMoonshot    ModelOwner = "moonshot"
	ModelOwnerMiniMax     ModelOwner = "minimax"
	ModelOwnerBaidu       ModelOwner = "baidu"
	ModelOwnerGoogle      ModelOwner = "google"
	ModelOwnerBAAI        ModelOwner = "baai"
	ModelOwnerFunAudioLLM ModelOwner = "funaudiollm"
	ModelOwnerDoubao      ModelOwner = "doubao"
	ModelOwnerFishAudio   ModelOwner = "fishaudio"
	ModelOwnerChatGLM     ModelOwner = "chatglm"
	ModelOwnerStabilityAI ModelOwner = "stabilityai"
	ModelOwnerNetease     ModelOwner = "netease"
	ModelOwnerAI360       ModelOwner = "ai360"
	ModelOwnerAnthropic   ModelOwner = "anthropic"
	ModelOwnerMeta        ModelOwner = "meta"
	ModelOwnerBaichuan    ModelOwner = "baichuan"
	ModelOwnerMistral     ModelOwner = "mistral"
	ModelOwnerOpenChat    ModelOwner = "openchat"
	ModelOwnerMicrosoft   ModelOwner = "microsoft"
	ModelOwnerDefog       ModelOwner = "defog"
	ModelOwnerNexusFlow   ModelOwner = "nexusflow"
	ModelOwnerCohere      ModelOwner = "cohere"
	ModelOwnerHuggingFace ModelOwner = "huggingface"
	ModelOwnerLingyiWanwu ModelOwner = "lingyiwanwu"
	ModelOwnerStepFun     ModelOwner = "stepfun"
	ModelOwnerXAI         ModelOwner = "xai"
	ModelOwnerDoc2x       ModelOwner = "doc2x"
	ModelOwnerJina        ModelOwner = "jina"
	ModelOwnerVoyage      ModelOwner = "voyage"
	ModelOwnerAntGroup    ModelOwner = "antgroup"
)

type Option

type Option struct {
	Key   string `gorm:"size:64;primaryKey" json:"key"`
	Value string `gorm:"type:text"          json:"value"`
}

func GetAllOption

func GetAllOption() ([]*Option, error)

func GetOption

func GetOption(key string) (*Option, error)

type Params

type Params = map[string]string

type Price

type Price struct {
	PerRequestPrice ZeroNullFloat64 `json:"per_request_price,omitempty"`

	InputPrice     ZeroNullFloat64 `json:"input_price,omitempty"`
	InputPriceUnit ZeroNullInt64   `json:"input_price_unit,omitempty"`

	ImageInputPrice     ZeroNullFloat64 `json:"image_input_price,omitempty"`
	ImageInputPriceUnit ZeroNullInt64   `json:"image_input_price_unit,omitempty"`

	AudioInputPrice     ZeroNullFloat64 `json:"audio_input_price,omitempty"`
	AudioInputPriceUnit ZeroNullInt64   `json:"audio_input_price_unit,omitempty"`

	VideoInputPrice     ZeroNullFloat64 `json:"video_input_price,omitempty"`
	VideoInputPriceUnit ZeroNullInt64   `json:"video_input_price_unit,omitempty"`

	OutputPrice     ZeroNullFloat64 `json:"output_price,omitempty"`
	OutputPriceUnit ZeroNullInt64   `json:"output_price_unit,omitempty"`

	ImageOutputPrice     ZeroNullFloat64 `json:"image_output_price,omitempty"`
	ImageOutputPriceUnit ZeroNullInt64   `json:"image_output_price_unit,omitempty"`

	AudioOutputPrice     ZeroNullFloat64 `json:"audio_output_price,omitempty"`
	AudioOutputPriceUnit ZeroNullInt64   `json:"audio_output_price_unit,omitempty"`

	// when ThinkingModeOutputPrice and ReasoningTokens are not 0, OutputPrice and OutputPriceUnit
	// will be overwritten
	ThinkingModeOutputPrice     ZeroNullFloat64 `json:"thinking_mode_output_price,omitempty"`
	ThinkingModeOutputPriceUnit ZeroNullInt64   `json:"thinking_mode_output_price_unit,omitempty"`

	CachedPrice     ZeroNullFloat64 `json:"cached_price,omitempty"`
	CachedPriceUnit ZeroNullInt64   `json:"cached_price_unit,omitempty"`

	CacheCreationPrice     ZeroNullFloat64 `json:"cache_creation_price,omitempty"`
	CacheCreationPriceUnit ZeroNullInt64   `json:"cache_creation_price_unit,omitempty"`

	WebSearchPrice     ZeroNullFloat64 `json:"web_search_price,omitempty"`
	WebSearchPriceUnit ZeroNullInt64   `json:"web_search_price_unit,omitempty"`

	ConditionalPrices []ConditionalPrice `gorm:"serializer:fastjson;type:text" json:"conditional_prices,omitempty"`
}

func (*Price) GetAudioInputPriceUnit

func (p *Price) GetAudioInputPriceUnit() int64

func (*Price) GetAudioOutputPriceUnit

func (p *Price) GetAudioOutputPriceUnit() int64

func (*Price) GetCacheCreationPriceUnit

func (p *Price) GetCacheCreationPriceUnit() int64

func (*Price) GetCachedPriceUnit

func (p *Price) GetCachedPriceUnit() int64

func (*Price) GetImageInputPriceUnit

func (p *Price) GetImageInputPriceUnit() int64

func (*Price) GetImageOutputPriceUnit

func (p *Price) GetImageOutputPriceUnit() int64

func (*Price) GetInputPriceUnit

func (p *Price) GetInputPriceUnit() int64

func (*Price) GetOutputPriceUnit

func (p *Price) GetOutputPriceUnit() int64

func (*Price) GetVideoInputPriceUnit

func (p *Price) GetVideoInputPriceUnit() int64

func (*Price) GetWebSearchPriceUnit

func (p *Price) GetWebSearchPriceUnit() int64

func (*Price) SelectConditionalPrice

func (p *Price) SelectConditionalPrice(
	usage Usage,
	usageContext UsageContext,
) Price

func (*Price) SelectConditionalPriceWithOptions

func (p *Price) SelectConditionalPriceWithOptions(
	usage Usage,
	usageContext UsageContext,
	options PriceSelectionOptions,
) Price

func (*Price) ValidateConditionalPrices

func (p *Price) ValidateConditionalPrices() error

type PriceCondition

type PriceCondition struct {
	InputTokenMin  int64    `json:"input_token_min,omitempty"`
	InputTokenMax  int64    `json:"input_token_max,omitempty"`
	OutputTokenMin int64    `json:"output_token_min,omitempty"`
	OutputTokenMax int64    `json:"output_token_max,omitempty"`
	StartTime      int64    `json:"start_time,omitempty"`       // Unix timestamp, 0 means no start limit
	EndTime        int64    `json:"end_time,omitempty"`         // Unix timestamp, 0 means no end limit
	DailyStartTime string   `json:"daily_start_time,omitempty"` // HH:mm, inclusive
	DailyEndTime   string   `json:"daily_end_time,omitempty"`   // HH:mm, exclusive; earlier than start crosses midnight
	Timezone       string   `json:"timezone,omitempty"`         // IANA timezone for the daily time range
	Resolution     []string `json:"resolution,omitempty"`
	Quality        []string `json:"quality,omitempty"`
	ServiceTier    string   `json:"service_tier,omitempty"`
	InputMedia     *bool    `json:"input_media,omitempty"`
	InputVideo     *bool    `json:"input_video,omitempty"`
	OutputAudio    *bool    `json:"output_audio,omitempty"`
}

type PriceSelectionOptions

type PriceSelectionOptions struct {
	DisableResolutionFuzzyMatch bool
	RequestAt                   time.Time
}

type ProxyParamType

type ProxyParamType string
const (
	ParamTypeURL    ProxyParamType = "url"
	ParamTypeHeader ProxyParamType = "header"
	ParamTypeQuery  ProxyParamType = "query"
)

type PublicMCP

type PublicMCP struct {
	ID                     string                  `gorm:"primaryKey"           json:"id"`
	CreatedAt              time.Time               `gorm:"index,autoCreateTime" json:"created_at"`
	UpdateAt               time.Time               `gorm:"index,autoUpdateTime" json:"update_at"`
	PublicMCPReusingParams []PublicMCPReusingParam `gorm:"foreignKey:MCPID"     json:"-"`

	Name          string          `json:"name"`
	NameCN        string          `json:"name_cn,omitempty"`
	Status        PublicMCPStatus `json:"status"                   gorm:"index;default:1"`
	Type          PublicMCPType   `json:"type,omitempty"           gorm:"index"`
	Description   string          `json:"description"`
	DescriptionCN string          `json:"description_cn,omitempty"`
	GitHubURL     string          `json:"github_url"`
	Readme        string          `json:"readme,omitempty"         gorm:"type:text"`
	ReadmeCN      string          `json:"readme_cn,omitempty"      gorm:"type:text"`
	ReadmeURL     string          `json:"readme_url,omitempty"`
	ReadmeCNURL   string          `json:"readme_cn_url,omitempty"`
	Tags          []string        `json:"tags,omitempty"           gorm:"serializer:fastjson;type:text"`
	LogoURL       string          `json:"logo_url,omitempty"`
	Price         MCPPrice        `json:"price"                    gorm:"embedded"`

	ProxyConfig   *PublicMCPProxyConfig `gorm:"serializer:fastjson;type:text" json:"proxy_config,omitempty"`
	OpenAPIConfig *MCPOpenAPIConfig     `gorm:"serializer:fastjson;type:text" json:"openapi_config,omitempty"`
	EmbedConfig   *MCPEmbeddingConfig   `gorm:"serializer:fastjson;type:text" json:"embed_config,omitempty"`
	// only used by list tools
	TestConfig *TestConfig `gorm:"serializer:fastjson;type:text" json:"test_config,omitempty"`
}

func GetAllPublicMCPs

func GetAllPublicMCPs(status PublicMCPStatus) ([]PublicMCP, error)

func GetPublicMCPByID

func GetPublicMCPByID(id string) (PublicMCP, error)

GetPublicMCPByID retrieves an MCP by ID

func GetPublicMCPs

func GetPublicMCPs(
	page, perPage int,
	id string,
	mcpType []PublicMCPType,
	keyword string,
	status PublicMCPStatus,
) (mcps []PublicMCP, total int64, err error)

GetPublicMCPs retrieves MCPs with pagination and filtering

func (*PublicMCP) BeforeCreate

func (p *PublicMCP) BeforeCreate(_ *gorm.DB) error

func (*PublicMCP) BeforeDelete

func (p *PublicMCP) BeforeDelete(tx *gorm.DB) (err error)

func (*PublicMCP) BeforeSave

func (p *PublicMCP) BeforeSave(_ *gorm.DB) error

func (*PublicMCP) ToPublicMCPCache

func (p *PublicMCP) ToPublicMCPCache() *PublicMCPCache

type PublicMCPCache

type PublicMCPCache struct {
	ID            string                `json:"id"             redis:"i"`
	Status        PublicMCPStatus       `json:"status"         redis:"s"`
	Type          PublicMCPType         `json:"type"           redis:"t"`
	Price         MCPPrice              `json:"price"          redis:"p"`
	ProxyConfig   *PublicMCPProxyConfig `json:"proxy_config"   redis:"pc"`
	OpenAPIConfig *MCPOpenAPIConfig     `json:"openapi_config" redis:"oc"`
	EmbedConfig   *MCPEmbeddingConfig   `json:"embed_config"   redis:"ec"`
}

func CacheGetPublicMCP

func CacheGetPublicMCP(mcpID string) (*PublicMCPCache, error)

type PublicMCPProxyConfig

type PublicMCPProxyConfig struct {
	URL     string                                `json:"url"`
	Querys  map[string]string                     `json:"querys"`
	Headers map[string]string                     `json:"headers"`
	Reusing map[string]PublicMCPProxyReusingParam `json:"reusing"`
}

func (*PublicMCPProxyConfig) MarshalBinary

func (c *PublicMCPProxyConfig) MarshalBinary() ([]byte, error)

func (*PublicMCPProxyConfig) ScanRedis

func (c *PublicMCPProxyConfig) ScanRedis(value string) error

type PublicMCPProxyReusingParam

type PublicMCPProxyReusingParam struct {
	ReusingParam
	Type ProxyParamType `json:"type"`
}

type PublicMCPReusingParam

type PublicMCPReusingParam struct {
	MCPID     string    `gorm:"primaryKey"                    json:"mcp_id"`
	GroupID   string    `gorm:"primaryKey"                    json:"group_id"`
	CreatedAt time.Time `gorm:"index"                         json:"created_at"`
	UpdateAt  time.Time `gorm:"index"                         json:"update_at"`
	Group     *Group    `gorm:"foreignKey:GroupID"            json:"-"`
	Params    Params    `gorm:"serializer:fastjson;type:text" json:"params"`
}

func GetPublicMCPReusingParam

func GetPublicMCPReusingParam(mcpID, groupID string) (PublicMCPReusingParam, error)

GetPublicMCPReusingParam retrieves a GroupMCPReusingParam by MCP ID and Group ID

func (*PublicMCPReusingParam) BeforeCreate

func (p *PublicMCPReusingParam) BeforeCreate(_ *gorm.DB) (err error)

func (*PublicMCPReusingParam) MarshalJSON

func (p *PublicMCPReusingParam) MarshalJSON() ([]byte, error)

func (*PublicMCPReusingParam) ToPublicMCPReusingParamCache

func (p *PublicMCPReusingParam) ToPublicMCPReusingParamCache() PublicMCPReusingParamCache

type PublicMCPReusingParamCache

type PublicMCPReusingParamCache struct {
	MCPID   string                   `json:"mcp_id"   redis:"m"`
	GroupID string                   `json:"group_id" redis:"g"`
	Params  redisMap[string, string] `json:"params"   redis:"p"`
}

func CacheGetPublicMCPReusingParam

func CacheGetPublicMCPReusingParam(mcpID, groupID string) (PublicMCPReusingParamCache, error)

type PublicMCPStatus

type PublicMCPStatus int
const (
	PublicMCPStatusEnabled PublicMCPStatus = iota + 1
	PublicMCPStatusDisabled
)

func (PublicMCPStatus) MarshalBinary

func (s PublicMCPStatus) MarshalBinary() ([]byte, error)

func (*PublicMCPStatus) ScanRedis

func (s *PublicMCPStatus) ScanRedis(value string) error

type PublicMCPType

type PublicMCPType string
const (
	PublicMCPTypeProxySSE        PublicMCPType = "mcp_proxy_sse"
	PublicMCPTypeProxyStreamable PublicMCPType = "mcp_proxy_streamable"
	PublicMCPTypeDocs            PublicMCPType = "mcp_docs" // read only
	PublicMCPTypeOpenAPI         PublicMCPType = "mcp_openapi"
	PublicMCPTypeEmbed           PublicMCPType = "mcp_embed"
)

func (PublicMCPType) MarshalBinary

func (t PublicMCPType) MarshalBinary() ([]byte, error)

func (*PublicMCPType) ScanRedis

func (t *PublicMCPType) ScanRedis(value string) error

type RequestDetail

type RequestDetail struct {
	CreatedAt             time.Time `gorm:"autoCreateTime;index" json:"-"`
	RequestBody           string    `gorm:"type:text"            json:"request_body,omitempty"`
	ResponseBody          string    `gorm:"type:text"            json:"response_body,omitempty"`
	RequestBodyTruncated  bool      `                            json:"request_body_truncated,omitempty"`
	ResponseBodyTruncated bool      `                            json:"response_body_truncated,omitempty"`
	ID                    int       `gorm:"primaryKey"           json:"id"`
	LogID                 int       `gorm:"index"                json:"log_id"`
}

func GetGroupChannelLogDetail

func GetGroupChannelLogDetail(logID int) (*RequestDetail, error)

func GetGroupChannelLogDetailForGroup

func GetGroupChannelLogDetailForGroup(logID int, group string) (*RequestDetail, error)

func GetGroupLogDetail

func GetGroupLogDetail(logID int, group string) (*RequestDetail, error)

func GetLogDetail

func GetLogDetail(logID int) (*RequestDetail, error)

func (*RequestDetail) ApplyBodySizeLimits

func (d *RequestDetail) ApplyBodySizeLimits(requestMaxSize, responseMaxSize int64)

func (*RequestDetail) DropInvalidUTF8Bodies

func (d *RequestDetail) DropInvalidUTF8Bodies()

type RetryLog

type RetryLog struct {
	RequestBody           string          `gorm:"type:text"                                         json:"request_body,omitempty"`
	ResponseBody          string          `gorm:"type:text"                                         json:"response_body,omitempty"`
	RequestBodyTruncated  bool            `                                                         json:"request_body_truncated,omitempty"`
	ResponseBodyTruncated bool            `                                                         json:"response_body_truncated,omitempty"`
	RequestAt             time.Time       `                                                         json:"request_at"`
	RetryAt               time.Time       `                                                         json:"retry_at,omitempty"`
	TTFBMilliseconds      ZeroNullInt64   `                                                         json:"ttfb_milliseconds,omitempty"`
	CreatedAt             time.Time       `gorm:"autoCreateTime;index"                              json:"created_at"`
	Model                 string          `gorm:"size:128"                                          json:"model"`
	RequestID             EmptyNullString `gorm:"type:char(16);index:,where:request_id is not null" json:"request_id"`
	ID                    int             `gorm:"primaryKey"                                        json:"id"`
	ChannelID             int             `                                                         json:"channel,omitempty"`
	Code                  int             `gorm:"index"                                             json:"code,omitempty"`
	Mode                  int             `                                                         json:"mode,omitempty"`
	RetryTimes            ZeroNullInt64   `                                                         json:"retry_times,omitempty"`
}

func (*RetryLog) MarshalJSON

func (r *RetryLog) MarshalJSON() ([]byte, error)

type ReusingParam

type ReusingParam struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	Required    bool   `json:"required"`
}

type SaveStoreOption

type SaveStoreOption struct {
	MinUpdateInterval time.Duration
}

type StoreCache

type StoreCache struct {
	ID        string    `json:"id"         redis:"i"`
	GroupID   string    `json:"group_id"   redis:"g"`
	TokenID   int       `json:"token_id"   redis:"t"`
	ChannelID int       `json:"channel_id" redis:"c"`
	Model     string    `json:"model"      redis:"m"`
	Metadata  string    `json:"metadata"   redis:"d"`
	CreatedAt time.Time `json:"created_at" redis:"a"`
	UpdatedAt time.Time `json:"updated_at" redis:"u"`
	ExpiresAt time.Time `json:"expires_at" redis:"e"`
}

func CacheGetStore

func CacheGetStore(group string, tokenID int, id string) (*StoreCache, error)

func CacheGetStoreByScope

func CacheGetStoreByScope(
	group string,
	tokenID int,
	id string,
	scope ChannelScope,
) (*StoreCache, error)

func (*StoreCache) ToStoreV2

func (s *StoreCache) ToStoreV2() *StoreV2

type StoreV2

type StoreV2 struct {
	ID        string    `gorm:"size:128;primaryKey:3"`
	CreatedAt time.Time `gorm:"autoCreateTime"`
	UpdatedAt time.Time `gorm:"autoUpdateTime"`
	ExpiresAt time.Time `gorm:"index"`
	GroupID   string    `gorm:"size:64;primaryKey:1"`
	TokenID   int       `gorm:"primaryKey:2"`
	ChannelID int
	Model     string `gorm:"size:128"`
	Metadata  string `gorm:"type:text"`
}

StoreV2 represents channel-associated data storage for various purposes: - Video generation jobs and their results - File storage with associated metadata - Any other channel-specific data that needs persistence

func GetStore

func GetStore(group string, tokenID int, id string) (*StoreV2, error)

func GetStoreByScope

func GetStoreByScope(group string, tokenID int, id string, scope ChannelScope) (*StoreV2, error)

func SaveIfNotExistStore

func SaveIfNotExistStore(s *StoreV2) (*StoreV2, error)

func SaveIfNotExistStoreByScope

func SaveIfNotExistStoreByScope(s *StoreV2, scope ChannelScope) (*StoreV2, error)

func SaveStore

func SaveStore(s *StoreV2) (*StoreV2, error)

func SaveStoreByScope

func SaveStoreByScope(s *StoreV2, scope ChannelScope) (*StoreV2, error)

func SaveStoreWithOption

func SaveStoreWithOption(s *StoreV2, opt SaveStoreOption) (*StoreV2, error)

func SaveStoreWithOptionByScope

func SaveStoreWithOptionByScope(
	s *StoreV2,
	scope ChannelScope,
	opt SaveStoreOption,
) (*StoreV2, error)

func (*StoreV2) BeforeSave

func (s *StoreV2) BeforeSave(_ *gorm.DB) error

func (*StoreV2) ToStoreCache

func (s *StoreV2) ToStoreCache() *StoreCache

type Summary

type Summary struct {
	ID     int           `gorm:"primaryKey"`
	Unique SummaryUnique `gorm:"embedded"`
	Data   SummaryData   `gorm:"embedded"`
}

only summary result only requests

func (*Summary) BeforeCreate

func (l *Summary) BeforeCreate(_ *gorm.DB) (err error)

type SummaryData

type SummaryData struct {
	SummaryDataSet
	ServiceTierFlex     SummaryDataSet `json:"service_tier_flex,omitempty"     gorm:"embedded;embeddedPrefix:service_tier_flex_"`
	ServiceTierPriority SummaryDataSet `json:"service_tier_priority,omitempty" gorm:"embedded;embeddedPrefix:service_tier_priority_"`
	ClaudeLongContext   SummaryDataSet `json:"claude_long_context,omitempty"   gorm:"embedded;embeddedPrefix:claude_long_context_"`
}

func (*SummaryData) Add

func (d *SummaryData) Add(other SummaryData)

func (*SummaryData) AddClaudeLongContextBreakdown

func (d *SummaryData) AddClaudeLongContextBreakdown(
	usage Usage,
	amount Amount,
	isRetry bool,
	status int,
)

func (*SummaryData) AddServiceTierBreakdown

func (d *SummaryData) AddServiceTierBreakdown(
	serviceTier string,
	usage Usage,
	amount Amount,
	totalTimeMilliseconds int64,
	totalTTFBMilliseconds int64,
	isRetry bool,
	status int,
)

type SummaryDataSet

type SummaryDataSet struct {
	Count                 `      json:",inline"                           gorm:"embedded"`
	Usage                 `      json:",inline"                           gorm:"embedded"`
	Amount                `      json:",inline"                           gorm:"embedded"`
	TotalTimeMilliseconds int64 `json:"total_time_milliseconds,omitempty"`
	TotalTTFBMilliseconds int64 `json:"total_ttfb_milliseconds,omitempty"`
}

func (*SummaryDataSet) Add

func (s *SummaryDataSet) Add(other SummaryDataSet)

type SummaryDataV2

type SummaryDataV2 struct {
	Timestamp      int64  `json:"timestamp,omitempty"`
	ChannelID      int    `json:"channel_id,omitempty"`
	GroupChannelID int    `json:"group_channel_id,omitempty"`
	GroupID        string `json:"group_id,omitempty"`
	TokenName      string `json:"token_name,omitempty"`
	Model          string `json:"model"`

	SummaryDataSet
	ServiceTierFlex     SummaryDataSet `json:"service_tier_flex,omitempty"     gorm:"embedded;embeddedPrefix:service_tier_flex_"`
	ServiceTierPriority SummaryDataSet `json:"service_tier_priority,omitempty" gorm:"embedded;embeddedPrefix:service_tier_priority_"`
	ClaudeLongContext   SummaryDataSet `json:"claude_long_context,omitempty"   gorm:"embedded;embeddedPrefix:claude_long_context_"`

	MaxRPM int64 `json:"max_rpm"`
	MaxTPM int64 `json:"max_tpm"`
}

type SummaryMinute

type SummaryMinute struct {
	ID     int                 `gorm:"primaryKey"`
	Unique SummaryMinuteUnique `gorm:"embedded"`
	Data   SummaryData         `gorm:"embedded"`
}

func (*SummaryMinute) BeforeCreate

func (l *SummaryMinute) BeforeCreate(_ *gorm.DB) (err error)

type SummaryMinuteUnique

type SummaryMinuteUnique struct {
	ChannelID       int    `gorm:"not null;uniqueIndex:idx_summary_minute_unique,priority:1"`
	Model           string `gorm:"size:128;not null;uniqueIndex:idx_summary_minute_unique,priority:2"`
	MinuteTimestamp int64  `gorm:"not null;uniqueIndex:idx_summary_minute_unique,priority:3,sort:desc"`
}

type SummaryMinuteUpdate

type SummaryMinuteUpdate struct {
	SummaryMinuteUnique
	SummaryData
}

type SummarySelectFields

type SummarySelectFields []string

SummarySelectFields is a list of field names to select when querying summary data

func ParseSummaryFields

func ParseSummaryFields(fieldsStr string) SummarySelectFields

ParseSummaryFields parses a comma-separated string of field names into SummarySelectFields Returns nil (meaning all fields) if the input is empty Supports field groups: "count", "usage", "time", "all" Example: "request_count,exception_count,cache_hit_count" or "count,used_amount"

func (SummarySelectFields) BuildSelectFields

func (f SummarySelectFields) BuildSelectFields(timestampField string) string

BuildSelectFields generates SQL select clause based on selected fields timestampField should be "hour_timestamp" or "minute_timestamp" Security: Only fields in allSummaryFields whitelist are allowed to prevent SQL injection

func (SummarySelectFields) BuildSelectFieldsV2

func (f SummarySelectFields) BuildSelectFieldsV2(timestampField, groupFields string) string

BuildSelectFieldsV2 generates SQL select clause with additional grouping fields for V2 API groupFields should be fields like "channel_id, model" or "group_id, token_name, model"

func (SummarySelectFields) IsEmpty

func (f SummarySelectFields) IsEmpty() bool

IsEmpty checks if no fields are selected (nil or empty slice means all fields)

type SummaryUnique

type SummaryUnique struct {
	ChannelID     int    `gorm:"not null;uniqueIndex:idx_summary_unique,priority:1"`
	Model         string `gorm:"size:128;not null;uniqueIndex:idx_summary_unique,priority:2"`
	HourTimestamp int64  `gorm:"not null;uniqueIndex:idx_summary_unique,priority:3,sort:desc"`
}

type SummaryUpdate

type SummaryUpdate struct {
	SummaryUnique
	SummaryData
}

type TestConfig

type TestConfig struct {
	Enabled bool   `json:"enabled"`
	Params  Params `json:"params"`
}

type TimeSpanType

type TimeSpanType string
const (
	TimeSpanMinute TimeSpanType = "minute"
	TimeSpanHour   TimeSpanType = "hour"
	TimeSpanDay    TimeSpanType = "day"
	TimeSpanMonth  TimeSpanType = "month"
)

type TimeSummaryDataV2

type TimeSummaryDataV2 struct {
	Timestamp int64           `json:"timestamp"`
	Summary   []SummaryDataV2 `json:"summary"`
}

func GetGlobalGroupChannelTimeSeriesModelData

func GetGlobalGroupChannelTimeSeriesModelData(
	group string,
	groupChannelID int,
	modelName string,
	start, end time.Time,
	timeSpan TimeSpanType,
	timezone *time.Location,
	fields SummarySelectFields,
) ([]TimeSummaryDataV2, error)

func GetGlobalGroupChannelTokenTimeSeriesModelData

func GetGlobalGroupChannelTokenTimeSeriesModelData(
	group string,
	tokenName string,
	modelName string,
	start, end time.Time,
	timeSpan TimeSpanType,
	timezone *time.Location,
	fields SummarySelectFields,
) ([]TimeSummaryDataV2, error)

func GetGroupChannelTimeSeriesModelData

func GetGroupChannelTimeSeriesModelData(
	group string,
	groupChannelID int,
	modelName string,
	start, end time.Time,
	timeSpan TimeSpanType,
	timezone *time.Location,
	fields SummarySelectFields,
) ([]TimeSummaryDataV2, error)

func GetGroupChannelTokenTimeSeriesModelData

func GetGroupChannelTokenTimeSeriesModelData(
	group string,
	tokenName string,
	modelName string,
	start, end time.Time,
	timeSpan TimeSpanType,
	timezone *time.Location,
	fields SummarySelectFields,
) ([]TimeSummaryDataV2, error)

func GetGroupTimeSeriesModelData

func GetGroupTimeSeriesModelData(
	group string,
	tokenName string,
	modelName string,
	start, end time.Time,
	timeSpan TimeSpanType,
	timezone *time.Location,
	fields SummarySelectFields,
) ([]TimeSummaryDataV2, error)

func GetTimeSeriesModelData

func GetTimeSeriesModelData(
	channelID int,
	modelName string,
	start, end time.Time,
	timeSpan TimeSpanType,
	timezone *time.Location,
	fields SummarySelectFields,
) ([]TimeSummaryDataV2, error)

type TimeoutConfig

type TimeoutConfig struct {
	RequestTimeout       int64 `json:"request_timeout,omitempty"        yaml:"request_timeout,omitempty"`
	StreamRequestTimeout int64 `json:"stream_request_timeout,omitempty" yaml:"stream_request_timeout,omitempty"`
}

type Token

type Token struct {
	CreatedAt          time.Time       `json:"created_at"`
	Group              *Group          `json:"-"                    gorm:"foreignKey:GroupID"`
	Key                string          `json:"key"                  gorm:"type:char(48);uniqueIndex"`
	Name               EmptyNullString `json:"name"                 gorm:"size:32;index;uniqueIndex:idx_group_name;not null"`
	GroupID            string          `json:"group"                gorm:"size:64;index;uniqueIndex:idx_group_name"`
	Scope              ChannelScope    `json:"scope"                gorm:"size:16;index"`
	Subnets            []string        `json:"subnets"              gorm:"serializer:fastjson;type:text"`
	Models             []string        `json:"models"               gorm:"serializer:fastjson;type:text"`
	Sets               []string        `json:"sets"                 gorm:"serializer:fastjson;type:text"`
	GroupChannelModels []string        `json:"group_channel_models" gorm:"serializer:fastjson;type:text"`
	GroupChannelSets   []string        `json:"group_channel_sets"   gorm:"serializer:fastjson;type:text"`
	Status             int             `json:"status"               gorm:"default:1;index"`
	ID                 int             `json:"id"                   gorm:"primaryKey"`

	UsedAmount               float64 `json:"used_amount"                 gorm:"index"`
	RequestCount             int     `json:"request_count"               gorm:"index"`
	GroupChannelUsedAmount   float64 `json:"group_channel_used_amount"   gorm:"index"`
	GroupChannelRequestCount int     `json:"group_channel_request_count" gorm:"index"`

	Quota                  float64         `json:"quota"`
	PeriodQuota            float64         `json:"period_quota"`
	PeriodType             EmptyNullString `json:"period_type"               gorm:"size:20"` // daily, weekly, monthly, default is monthly
	PeriodLastUpdateTime   time.Time       `json:"period_last_update_time"`                  // Last time period was reset
	PeriodLastUpdateAmount float64         `json:"period_last_update_amount"`                // Total usage at last period reset
}

func GetGroupTokenByID

func GetGroupTokenByID(group string, id int) (*Token, error)

func GetTokenByID

func GetTokenByID(id int) (*Token, error)

func GetTokenByKey

func GetTokenByKey(key string) (*Token, error)

func GetTokens

func GetTokens(
	group string,
	page, perPage int,
	order string,
	status int,
) (tokens []*Token, total int64, err error)

func SearchGroupTokens

func SearchGroupTokens(
	group, keyword string,
	page, perPage int,
	order string,
	status int,
	name, key string,
) (tokens []*Token, total int64, err error)

func SearchTokens

func SearchTokens(
	group, keyword string,
	page, perPage int,
	order string,
	status int,
	name, key string,
) (tokens []*Token, total int64, err error)

func UpdateGroupToken

func UpdateGroupToken(
	id int,
	group string,
	update UpdateTokenRequest,
) (token *Token, err error)

func UpdateToken

func UpdateToken(id int, update UpdateTokenRequest) (token *Token, err error)

func (*Token) BeforeCreate

func (t *Token) BeforeCreate(_ *gorm.DB) error

func (*Token) BeforeSave

func (t *Token) BeforeSave(_ *gorm.DB) error

func (*Token) GetEffectiveQuotaStatus

func (t *Token) GetEffectiveQuotaStatus() (totalExceeded, periodExceeded bool, err error)

GetEffectiveQuotaStatus returns the effective quota status for token

func (*Token) NeedsPeriodReset

func (t *Token) NeedsPeriodReset() (bool, error)

NeedsPeriodReset checks if the period usage should be reset Uses PeriodLastUpdateTime to determine when the last period reset occurred

func (*Token) ToTokenCache

func (t *Token) ToTokenCache() *TokenCache

type TokenCache

type TokenCache struct {
	Group              string           `json:"group"                redis:"g"`
	Key                string           `json:"-"                    redis:"-"`
	Name               string           `json:"name"                 redis:"n"`
	Scope              ChannelScope     `json:"scope"                redis:"sc"`
	Subnets            redisStringSlice `json:"subnets"              redis:"s"`
	Models             redisStringSlice `json:"models"               redis:"m"`
	Sets               redisStringSlice `json:"sets"                 redis:"sets"`
	GroupChannelModels redisStringSlice `json:"group_channel_models" redis:"gcm"`
	GroupChannelSets   redisStringSlice `json:"group_channel_sets"   redis:"gcs"`
	ID                 int              `json:"id"                   redis:"i"`
	Status             int              `json:"status"               redis:"st"`
	UsedAmount         float64          `json:"used_amount"          redis:"u"`

	Quota                  float64   `json:"quota"                     redis:"q"`
	PeriodQuota            float64   `json:"period_quota"              redis:"pq"`
	PeriodType             string    `json:"period_type"               redis:"pt"`
	PeriodLastUpdateTime   redisTime `json:"period_last_update_time"   redis:"plut"`
	PeriodLastUpdateAmount float64   `json:"period_last_update_amount" redis:"plua"`
}

func CacheGetTokenByKey

func CacheGetTokenByKey(key string) (*TokenCache, error)

func GetAndValidateToken

func GetAndValidateToken(key string) (token *TokenCache, err error)

GetAndValidateToken validates a token and checks quota limits This function is safe for concurrent use and handles period resets atomically

func GetTokenByKeyForAuth

func GetTokenByKeyForAuth(key string) (token *TokenCache, err error)

func (*TokenCache) GetConfiguredGroupChannelSets

func (t *TokenCache) GetConfiguredGroupChannelSets() []string

func (*TokenCache) GetConfiguredSets

func (t *TokenCache) GetConfiguredSets() []string

type TokenUpdate

type TokenUpdate struct {
	Amount decimal.Decimal
	Count  int
}

type UpdateGroupRequest

type UpdateGroupRequest struct {
	Status                int       `json:"status"`
	RPMRatio              *float64  `json:"rpm_ratio,omitempty"`
	TPMRatio              *float64  `json:"tpm_ratio,omitempty"`
	AvailableSets         *[]string `json:"available_sets,omitempty"`
	BalanceAlertEnabled   *bool     `json:"balance_alert_enabled"`
	BalanceAlertThreshold *float64  `json:"balance_alert_threshold"`
}

type UpdateTokenRequest

type UpdateTokenRequest struct {
	Name               *string   `json:"name"`
	Subnets            *[]string `json:"subnets"`
	Models             *[]string `json:"models"`
	Sets               *[]string `json:"sets"`
	GroupChannelModels *[]string `json:"group_channel_models"`
	GroupChannelSets   *[]string `json:"group_channel_sets"`
	Scope              *string   `json:"scope"`
	Status             int       `json:"status"`
	// Quota system
	Quota                *float64 `json:"quota"`
	PeriodQuota          *float64 `json:"period_quota"`
	PeriodType           *string  `json:"period_type"`
	PeriodLastUpdateTime *int64   `json:"period_last_update_time"`
}

type Usage

type Usage struct {
	InputTokens         ZeroNullInt64 `json:"input_tokens,omitempty"`
	ImageInputTokens    ZeroNullInt64 `json:"image_input_tokens,omitempty"`
	AudioInputTokens    ZeroNullInt64 `json:"audio_input_tokens,omitempty"`
	VideoInputTokens    ZeroNullInt64 `json:"video_input_tokens,omitempty"`
	OutputTokens        ZeroNullInt64 `json:"output_tokens,omitempty"`
	ImageOutputTokens   ZeroNullInt64 `json:"image_output_tokens,omitempty"`
	AudioOutputTokens   ZeroNullInt64 `json:"audio_output_tokens,omitempty"`
	CachedTokens        ZeroNullInt64 `json:"cached_tokens,omitempty"`
	CacheCreationTokens ZeroNullInt64 `json:"cache_creation_tokens,omitempty"`
	ReasoningTokens     ZeroNullInt64 `json:"reasoning_tokens,omitempty"`
	TotalTokens         ZeroNullInt64 `json:"total_tokens,omitempty"`
	WebSearchCount      ZeroNullInt64 `json:"web_search_count,omitempty"`
}

func (*Usage) Add

func (u *Usage) Add(other Usage)

type UsageContext

type UsageContext struct {
	Resolution       string `gorm:"size:32" json:"resolution,omitempty"`
	NativeResolution string `gorm:"size:32" json:"native_resolution,omitempty"`
	Quality          string `gorm:"size:32" json:"quality,omitempty"`
	ServiceTier      string `gorm:"size:32" json:"service_tier,omitempty"`
	InputMedia       *bool  `               json:"input_media,omitempty"`
	InputVideo       *bool  `               json:"input_video,omitempty"`
	OutputAudio      *bool  `               json:"output_audio,omitempty"`
}

func (UsageContext) PriceConditionMatches

func (c UsageContext) PriceConditionMatches(condition PriceCondition) bool

func (UsageContext) WithFallback

func (c UsageContext) WithFallback(fallback UsageContext) UsageContext

type YAMLConfig

type YAMLConfig struct {
	Channels     []ChannelItem     `yaml:"channels,omitempty"`
	ModelConfigs []ModelConfigItem `yaml:"modelconfigs,omitempty"`
	Options      map[string]string `yaml:"options,omitempty"`
}

YAMLConfig represents the complete configuration with proper types

func LoadYAMLConfig

func LoadYAMLConfig() *YAMLConfig

LoadYAMLConfig loads and parses YAML configuration with proper types Uses a 60-second cache with double-check locking for performance

type ZeroNullFloat64

type ZeroNullFloat64 float64

func (*ZeroNullFloat64) Scan

func (znf *ZeroNullFloat64) Scan(value any) error

func (ZeroNullFloat64) Value

func (znf ZeroNullFloat64) Value() (driver.Value, error)

type ZeroNullInt64

type ZeroNullInt64 int64

func (*ZeroNullInt64) Scan

func (zni *ZeroNullInt64) Scan(value any) error

func (ZeroNullInt64) Value

func (zni ZeroNullInt64) Value() (driver.Value, error)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL