Documentation
¶
Index ¶
- Constants
- Variables
- func BatchInsertChannels(channels []Channel) error
- func CacheDecreaseUserQuota(id int, quota int64) error
- func CacheGetGroupModels(ctx context.Context, group string) ([]string, error)
- func CacheGetUserGroup(id int) (group string, err error)
- func CacheGetUserQuota(ctx context.Context, id int) (quota int64, err error)
- func CacheIsUserEnabled(userId int) (bool, error)
- func CacheUpdateUserQuota(ctx context.Context, id int) error
- func ClearOldLogBodies(targetTimestamp int64) (int64, error)
- func CloseDB() error
- func CreateModelMetadata(metadata *ModelMetadata) error
- func CreateRootAccountIfNeed() error
- func DecreaseUserQuota(id int, quota int64) (err error)
- func DeleteChannelByStatus(status int64) (int64, error)
- func DeleteDisabledChannel() (int64, error)
- func DeleteModelMetadata(name string) error
- func DeleteOldLog(targetTimestamp int64) (int64, error)
- func DeleteTokenById(id int, userId int) (err error)
- func DeleteUserById(id int) (err error)
- func GetAllLogsCount(logType int, startTimestamp int64, endTimestamp int64, modelName string, ...) (total int64, err error)
- func GetGroupModels(ctx context.Context, group string) ([]string, error)
- func GetMaxUserId() int
- func GetModelEndpointTypes(modelName string) []apitype.EndpointType
- func GetRootUserEmail() (email string)
- func GetUserEmail(id int) (email string, err error)
- func GetUserGroup(id int) (group string, err error)
- func GetUserLogsCount(userId int, logType int, startTimestamp int64, endTimestamp int64, ...) (total int64, err error)
- func GetUserQuota(id int) (quota int64, err error)
- func GetUserUsedQuota(id int) (quota int64, err error)
- func GetUsernameById(id int) (username string)
- func IncreaseUserQuota(id int, quota int64) (err error)
- func InitBatchUpdater()
- func InitChannelCache()
- func InitDB()
- func InitLogDB()
- func InitModelMetadataMap()
- func InitOptionMap()
- func IsAdmin(userId int) bool
- func IsEmailAlreadyTaken(email string) bool
- func IsMetadataExists(name string) bool
- func IsUserEnabled(userId int) (bool, error)
- func IsUsernameAlreadyTaken(username string) bool
- func PostConsumeResetUserQuotaCache(ctx context.Context, userId int, consumedQuota int64)
- func RecordConsumeLog(ctx context.Context, log *Log)
- func RecordLog(ctx context.Context, userId int, logType int, content string)
- func RecordTestLog(ctx context.Context, log *Log)
- func RefreshModelMetadataMap()
- func ResetUserPasswordByEmail(email string, password string) error
- func SimplifyModelName(modelName string) string
- func SimplifyModelsField(models *string) *string
- func SumUsedQuota(logType int, startTimestamp int64, endTimestamp int64, modelName string, ...) (quota int64)
- func SumUsedToken(logType int, startTimestamp int64, endTimestamp int64, modelName string, ...) (token int)
- func SumUserQuotaTotal(userId int) (token int)
- func SyncChannelCache(frequency int)
- func SyncOptions(frequency int)
- func UpdateAbilityStatus(channelId int, status bool) error
- func UpdateChannelStatusById(id int, status int)
- func UpdateChannelUsedQuota(id int, quota int64)
- func UpdateModelMetadata(metadata *ModelMetadata) error
- func UpdateOption(key string, value string) error
- func UpdateUserUsedQuotaAndRequestCount(id int, quota int64)
- type Ability
- type Channel
- func CacheGetGroupChannels(group string) []*Channel
- func CacheGetRandomSatisfiedChannel(group string, model string, ignoreFirstPriority bool) (*Channel, error)
- func GetAllChannels(startIdx int, num int, scope string) ([]*Channel, error)
- func GetChannelById(id int, selectAll bool) (*Channel, error)
- func GetChannelsByGroup(group string) ([]*Channel, error)
- func GetRandomSatisfiedChannel(group string, model string, ignoreFirstPriority bool) (*Channel, error)
- func SearchChannels(keyword string) (channels []*Channel, err error)
- func (channel *Channel) AddAbilities() error
- func (channel *Channel) Delete() error
- func (channel *Channel) DeleteAbilities() error
- func (channel *Channel) GetAlias() []string
- func (channel *Channel) GetBaseURL() string
- func (channel *Channel) GetModelMapping() map[string]string
- func (channel *Channel) GetModels() []string
- func (channel *Channel) GetPriority() int64
- func (channel *Channel) Insert() error
- func (channel *Channel) LoadConfig() (ChannelConfig, error)
- func (channel *Channel) Update() error
- func (channel *Channel) UpdateAbilities() error
- func (channel *Channel) UpdateBalance(balance float64)
- func (channel *Channel) UpdateResponseTime(responseTime int64)
- type ChannelConfig
- type Log
- type LogListItem
- func GetAllLogs(logType int, startTimestamp int64, endTimestamp int64, modelName string, ...) (logs []*LogListItem, err error)
- func GetUserLogs(userId int, logType int, startTimestamp int64, endTimestamp int64, ...) (logs []*LogListItem, err error)
- func SearchAllLogs(keyword string) (logs []*LogListItem, err error)
- func SearchUserLogs(userId int, keyword string) (logs []*LogListItem, err error)
- type LogStatistic
- type ModelMetadata
- type Option
- type Token
- func CacheGetTokenByKey(key string) (*Token, error)
- func GetAllUserTokens(userId int, startIdx int, num int) ([]*Token, error)
- func GetTokenById(id int) (*Token, error)
- func GetTokenByIds(id int, userId int) (*Token, error)
- func SearchUserTokens(userId int, keyword string) (tokens []*Token, err error)
- func ValidateUserToken(key string) (token *Token, err error)
- type User
- func (user *User) Delete() errordeprecated
- func (user *User) FillUserByEmail() error
- func (user *User) FillUserById() error
- func (user *User) FillUserByUsername() error
- func (user *User) Insert(ctx context.Context) error
- func (user *User) Update(updatePassword bool) error
- func (user *User) ValidateAndFill() (err error)
Constants ¶
const ( ChannelStatusUnknown = 0 ChannelStatusEnabled = 1 // don't use 0, 0 is the default value! ChannelStatusManuallyDisabled = 2 // also don't use 0 ChannelStatusAutoDisabled = 3 )
const ( LogTypeUnknown = iota // LogTypeTopup 充值/额度变更记录。原充值功能已移除,保留该常量以保持数据库旧数据一致。 LogTypeTopup LogTypeConsume LogTypeManage LogTypeSystem LogTypeTest )
const ( TokenStatusEnabled = 1 TokenStatusDisabled = 2 )
const ( RoleGuestUser = 0 RoleCommonUser = 1 RoleAdminUser = 10 RoleRootUser = 100 )
const ( UserStatusEnabled = 1 // don't use 0, 0 is the default value! UserStatusDisabled = 2 // also don't use 0 UserStatusDeleted = 3 )
const ( BatchUpdateTypeUserQuota = iota BatchUpdateTypeUsedQuota BatchUpdateTypeChannelUsedQuota BatchUpdateTypeRequestCount BatchUpdateTypeCount // if you add a new type, you need to add a new map and a new lock )
const ModelEndpointTypesKey = "ModelEndpointTypes"
Variables ¶
var ( TokenCacheSeconds = config.SyncFrequency UserId2GroupCacheSeconds = config.SyncFrequency UserId2QuotaCacheSeconds = config.SyncFrequency UserId2StatusCacheSeconds = config.SyncFrequency GroupModelsCacheSeconds = config.SyncFrequency )
var DB *gorm.DB
var LOG_DB *gorm.DB
Functions ¶
func BatchInsertChannels ¶
func CacheDecreaseUserQuota ¶
func CacheGetGroupModels ¶
func CacheGetUserGroup ¶
func CacheGetUserQuota ¶
func CacheIsUserEnabled ¶
func ClearOldLogBodies ¶
func CreateModelMetadata ¶
func CreateModelMetadata(metadata *ModelMetadata) error
func CreateRootAccountIfNeed ¶
func CreateRootAccountIfNeed() error
func DecreaseUserQuota ¶
func DeleteChannelByStatus ¶
func DeleteDisabledChannel ¶
func DeleteModelMetadata ¶
func DeleteOldLog ¶
func DeleteTokenById ¶
func DeleteUserById ¶
func GetAllLogsCount ¶
func GetMaxUserId ¶
func GetMaxUserId() int
func GetModelEndpointTypes ¶
func GetModelEndpointTypes(modelName string) []apitype.EndpointType
func GetRootUserEmail ¶
func GetRootUserEmail() (email string)
func GetUserEmail ¶
func GetUserGroup ¶
func GetUserLogsCount ¶
func GetUserQuota ¶
func GetUserUsedQuota ¶
func GetUsernameById ¶
func IncreaseUserQuota ¶
func InitBatchUpdater ¶
func InitBatchUpdater()
func InitChannelCache ¶
func InitChannelCache()
func InitModelMetadataMap ¶
func InitModelMetadataMap()
func InitOptionMap ¶
func InitOptionMap()
func IsEmailAlreadyTaken ¶
func IsMetadataExists ¶
func IsUserEnabled ¶
func IsUsernameAlreadyTaken ¶
func PostConsumeResetUserQuotaCache ¶
PostConsumeResetUserQuotaCache refreshes the cached user quota from DB after the quota has already been updated in DB.
func RecordConsumeLog ¶
func RecordTestLog ¶
func RefreshModelMetadataMap ¶
func RefreshModelMetadataMap()
func SimplifyModelName ¶
SimplifyModelName strips non-alphanumeric characters and lowercases the model name. This produces a simplified alias suitable for display or matching purposes.
func SimplifyModelsField ¶
func SumUsedQuota ¶
func SumUsedToken ¶
func SumUserQuotaTotal ¶
SumUserQuotaTotal sums the total quota consumed by a user from logs.
func SyncChannelCache ¶
func SyncChannelCache(frequency int)
func SyncOptions ¶
func SyncOptions(frequency int)
func UpdateAbilityStatus ¶
func UpdateChannelStatusById ¶
func UpdateChannelUsedQuota ¶
func UpdateModelMetadata ¶
func UpdateModelMetadata(metadata *ModelMetadata) error
func UpdateOption ¶
Types ¶
type Ability ¶
type Ability struct {
Group string `json:"group" gorm:"type:varchar(32);primaryKey;autoIncrement:false"`
Model string `json:"model" gorm:"primaryKey;autoIncrement:false"`
ChannelId int `json:"channel_id" gorm:"primaryKey;autoIncrement:false;index"`
Enabled bool `json:"enabled"`
Priority *int64 `json:"priority" gorm:"bigint;default:0;index"`
}
type Channel ¶
type Channel struct {
Id int `json:"id"`
Type int `json:"type" gorm:"default:0"`
Key string `json:"key" gorm:"type:text"`
Status int `json:"status" gorm:"default:1"`
Name string `json:"name" gorm:"index"`
Weight *uint `json:"weight" gorm:"default:0"`
CreatedTime int64 `json:"created_time" gorm:"bigint"`
TestTime int64 `json:"test_time" gorm:"bigint"`
ResponseTime int `json:"response_time"` // in milliseconds
BaseURL *string `json:"base_url" gorm:"column:base_url;default:''"`
Other *string `json:"other"` // DEPRECATED: please save config to field Config
Balance float64 `json:"balance"` // in USD
BalanceUpdatedTime int64 `json:"balance_updated_time" gorm:"bigint"`
Models string `json:"models"`
Group string `json:"group" gorm:"type:varchar(32);default:'default'"`
UsedQuota int64 `json:"used_quota" gorm:"bigint;default:0"`
ModelMapping *string `json:"model_mapping" gorm:"type:varchar(1024);default:''"`
Priority *int64 `json:"priority" gorm:"bigint;default:1"`
ModelsAlias string `json:"models_alias" gorm:"type:text"`
Config string `json:"config"`
SystemPrompt *string `json:"system_prompt" gorm:"type:text"`
// contains filtered or unexported fields
}
func CacheGetGroupChannels ¶
func GetChannelsByGroup ¶
func SearchChannels ¶
func (*Channel) AddAbilities ¶
func (*Channel) DeleteAbilities ¶
func (*Channel) GetBaseURL ¶
func (*Channel) GetModelMapping ¶
func (*Channel) GetPriority ¶
func (*Channel) LoadConfig ¶
func (channel *Channel) LoadConfig() (ChannelConfig, error)
func (*Channel) UpdateAbilities ¶
UpdateAbilities updates abilities of this channel. Make sure the channel is completed before calling this function.
func (*Channel) UpdateBalance ¶
func (*Channel) UpdateResponseTime ¶
type ChannelConfig ¶
type ChannelConfig struct {
Region string `json:"region,omitempty"`
SK string `json:"sk,omitempty"`
AK string `json:"ak,omitempty"`
UserID string `json:"user_id,omitempty"`
APIVersion string `json:"api_version,omitempty"`
LibraryID string `json:"library_id,omitempty"`
Plugin string `json:"plugin,omitempty"`
VertexAIProjectID string `json:"vertex_ai_project_id,omitempty"`
VertexAIADC string `json:"vertex_ai_adc,omitempty"`
}
type Log ¶
type Log struct {
Id int `json:"id"`
UserId int `json:"user_id" gorm:"index"`
CreatedAt int64 `json:"created_at" gorm:"bigint;index:idx_created_at_type"`
Type int `json:"type" gorm:"index:idx_created_at_type"`
Content string `json:"content"`
Username string `json:"username" gorm:"index:index_username_model_name,priority:2;default:''"`
TokenName string `json:"token_name" gorm:"index;default:''"`
ModelName string `json:"model_name" gorm:"index;index:index_username_model_name,priority:1;default:''"`
Quota int `json:"quota" gorm:"default:0"`
PromptTokens int `json:"prompt_tokens" gorm:"default:0"`
CompletionTokens int `json:"completion_tokens" gorm:"default:0"`
CachedTokens int `json:"cached_tokens" gorm:"default:0"` // 缓存命中的token数
ChannelId int `json:"channel" gorm:"index"`
RequestId string `json:"request_id" gorm:"default:''"`
ElapsedTime int64 `json:"elapsed_time" gorm:"default:0"` // unit is ms
IsStream bool `json:"is_stream" gorm:"default:false"`
SystemPromptReset bool `json:"system_prompt_reset" gorm:"default:false"`
ChannelName string `json:"channel_name" gorm:"default:''"`
RequestBody string `json:"request_body" gorm:"type:text"`
ResponseBody string `json:"response_body" gorm:"type:text"`
RequestHeader string `json:"request_header" gorm:"type:text"`
}
func GetLogById ¶
type LogListItem ¶
type LogListItem struct {
Id int `json:"id"`
UserId int `json:"user_id"`
CreatedAt int64 `json:"created_at"`
Type int `json:"type"`
Content string `json:"content"`
Username string `json:"username"`
TokenName string `json:"token_name"`
ModelName string `json:"model_name"`
Quota int `json:"quota"`
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
CachedTokens int `json:"cached_tokens"`
ChannelId int `json:"channel"`
RequestId string `json:"request_id"`
ElapsedTime int64 `json:"elapsed_time"`
IsStream bool `json:"is_stream"`
SystemPromptReset bool `json:"system_prompt_reset"`
ChannelName string `json:"channel_name"`
HasRequestBody bool `json:"has_request_body"`
HasResponseBody bool `json:"has_response_body"`
HasRequestHeader bool `json:"has_request_header"`
}
LogListItem 用于日志列表查询,包含三个 bool 字段用于标识大字段是否有内容 这个结构体不会参与数据库迁移,只用于查询结果的映射
func GetAllLogs ¶
func GetUserLogs ¶
func SearchAllLogs ¶
func SearchAllLogs(keyword string) (logs []*LogListItem, err error)
func SearchUserLogs ¶
func SearchUserLogs(userId int, keyword string) (logs []*LogListItem, err error)
func (LogListItem) TableName ¶
func (LogListItem) TableName() string
TableName 指定 LogListItem 查询时使用的表名
type LogStatistic ¶
type LogStatistic struct {
Day string `gorm:"column:day"`
ModelName string `gorm:"column:model_name"`
RequestCount int `gorm:"column:request_count"`
Quota int `gorm:"column:quota"`
PromptTokens int `gorm:"column:prompt_tokens"`
CompletionTokens int `gorm:"column:completion_tokens"`
}
func SearchLogsByDayAndModel ¶
func SearchLogsByDayAndModel(userId, start, end int) (LogStatistics []*LogStatistic, err error)
type ModelMetadata ¶
type ModelMetadata struct {
Name string `json:"name" gorm:"primaryKey"`
DisplayName string `json:"display_name"`
Visibility string `json:"visibility"`
SupportedInApi bool `json:"supported_in_api"`
Priority int `json:"priority"`
DefaultReasoningLevel string `json:"default_reasoning_level"`
SupportedReasoningLevels []string `json:"supported_reasoning_levels" gorm:"type:text"`
ContextWindow int `json:"context_window"`
TruncationPolicy string `json:"truncation_policy"`
InputModalities []string `json:"input_modalities" gorm:"type:text"`
OutputModalities []string `json:"output_modalities" gorm:"type:text"`
SupportedEndpointTypes []apitype.EndpointType `json:"supported_endpoint_types" gorm:"type:text"`
ApplyPatchToolType string `json:"apply_patch_tool_type"`
WebSearchToolType string `json:"web_search_tool_type"`
MaxOutputTokens int `json:"max_output_tokens"`
CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"`
}
func GetAllModelMetadata ¶
func GetAllModelMetadata() ([]*ModelMetadata, error)
func GetModelMetadata ¶
func GetModelMetadata(name string) (*ModelMetadata, error)
func GetModelMetadataBySimplifiedName ¶
func GetModelMetadataBySimplifiedName(simplifiedName string) *ModelMetadata
func GetOrCreateDefaultMetadata ¶
func GetOrCreateDefaultMetadata(simplifiedName string) *ModelMetadata
func (ModelMetadata) TableName ¶
func (ModelMetadata) TableName() string
type Token ¶
type Token struct {
Id int `json:"id"`
UserId int `json:"user_id"`
Key string `json:"key" gorm:"type:char(48);uniqueIndex"`
Status int `json:"status" gorm:"default:1"`
Name string `json:"name" gorm:"index" `
CreatedTime int64 `json:"created_time" gorm:"bigint"`
AccessedTime int64 `json:"accessed_time" gorm:"bigint"`
Models *string `json:"models" gorm:"type:text"` // allowed models
Subnet *string `json:"subnet" gorm:"default:''"` // allowed subnet
ModelMapping *string `json:"model_mapping" gorm:"type:varchar(1024);default:''"`
}
func CacheGetTokenByKey ¶
func GetTokenById ¶
func SearchUserTokens ¶
func ValidateUserToken ¶
func (*Token) GetModelMapping ¶
type User ¶
type User struct {
Id int `json:"id"`
Username string `json:"username" gorm:"unique;index" validate:"max=12"`
Password string `json:"password" gorm:"not null;" validate:"min=8,max=20"`
DisplayName string `json:"display_name" gorm:"index" validate:"max=20"`
Role int `json:"role" gorm:"type:int;default:1"` // admin, util
Status int `json:"status" gorm:"type:int;default:1"` // enabled, disabled
Email string `json:"email" gorm:"index" validate:"max=50"`
AccessToken string `json:"access_token" gorm:"type:char(32);column:access_token;uniqueIndex"` // this token is for system management
Quota int64 `json:"quota" gorm:"bigint;default:0"`
UsedQuota int64 `json:"used_quota" gorm:"bigint;default:0;column:used_quota"` // used quota
RequestCount int `json:"request_count" gorm:"type:int;default:0;"` // request number
Group string `json:"group" gorm:"type:varchar(32);default:'default'"`
}
User if you add sensitive fields, don't forget to clean them in setupLogin function. Otherwise, the sensitive information will be saved on local storage in plain text!
func SearchUsers ¶
func ValidateAccessToken ¶
func (*User) FillUserByEmail ¶
func (*User) FillUserById ¶
func (*User) FillUserByUsername ¶
func (*User) ValidateAndFill ¶
ValidateAndFill check password & user status