model

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 6, 2026 License: MIT Imports: 30 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	ChannelStatusUnknown          = 0
	ChannelStatusEnabled          = 1 // don't use 0, 0 is the default value!
	ChannelStatusManuallyDisabled = 2 // also don't use 0
	ChannelStatusAutoDisabled     = 3
)
View Source
const (
	LogTypeUnknown = iota
	// LogTypeTopup 充值/额度变更记录。原充值功能已移除,保留该常量以保持数据库旧数据一致。
	LogTypeTopup
	LogTypeConsume
	LogTypeManage
	LogTypeSystem
	LogTypeTest
)
View Source
const (
	TokenStatusEnabled  = 1
	TokenStatusDisabled = 2
)
View Source
const (
	RoleGuestUser  = 0
	RoleCommonUser = 1
	RoleAdminUser  = 10
	RoleRootUser   = 100
)
View Source
const (
	UserStatusEnabled  = 1 // don't use 0, 0 is the default value!
	UserStatusDisabled = 2 // also don't use 0
	UserStatusDeleted  = 3
)
View Source
const (
	BatchUpdateTypeUserQuota = iota
	BatchUpdateTypeUsedQuota
	BatchUpdateTypeChannelUsedQuota
	BatchUpdateTypeRequestCount
	BatchUpdateTypeCount // if you add a new type, you need to add a new map and a new lock
)
View Source
const ModelEndpointTypesKey = "ModelEndpointTypes"

Variables

View Source
var (
	TokenCacheSeconds         = config.SyncFrequency
	UserId2GroupCacheSeconds  = config.SyncFrequency
	UserId2QuotaCacheSeconds  = config.SyncFrequency
	UserId2StatusCacheSeconds = config.SyncFrequency
	GroupModelsCacheSeconds   = config.SyncFrequency
)
View Source
var DB *gorm.DB
View Source
var LOG_DB *gorm.DB

Functions

func BatchInsertChannels

func BatchInsertChannels(channels []Channel) error

func CacheDecreaseUserQuota

func CacheDecreaseUserQuota(id int, quota int64) error

func CacheGetGroupModels

func CacheGetGroupModels(ctx context.Context, group string) ([]string, error)

func CacheGetUserGroup

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

func CacheGetUserQuota

func CacheGetUserQuota(ctx context.Context, id int) (quota int64, err error)

func CacheIsUserEnabled

func CacheIsUserEnabled(userId int) (bool, error)

func CacheUpdateUserQuota

func CacheUpdateUserQuota(ctx context.Context, id int) error

func ClearOldLogBodies

func ClearOldLogBodies(targetTimestamp int64) (int64, error)

func CloseDB

func CloseDB() error

func CreateModelMetadata

func CreateModelMetadata(metadata *ModelMetadata) error

func CreateRootAccountIfNeed

func CreateRootAccountIfNeed() error

func DecreaseUserQuota

func DecreaseUserQuota(id int, quota int64) (err error)

func DeleteChannelByStatus

func DeleteChannelByStatus(status int64) (int64, error)

func DeleteDisabledChannel

func DeleteDisabledChannel() (int64, error)

func DeleteModelMetadata

func DeleteModelMetadata(name string) error

func DeleteOldLog

func DeleteOldLog(targetTimestamp int64) (int64, error)

func DeleteTokenById

func DeleteTokenById(id int, userId int) (err error)

func DeleteUserById

func DeleteUserById(id int) (err error)

func GetAllLogsCount

func GetAllLogsCount(logType int, startTimestamp int64, endTimestamp int64, modelName string, username string, tokenName string, channel int) (total int64, err error)

func GetGroupModels

func GetGroupModels(ctx context.Context, group string) ([]string, error)

func GetMaxUserId

func GetMaxUserId() int

func GetModelEndpointTypes

func GetModelEndpointTypes(modelName string) []apitype.EndpointType

func GetRootUserEmail

func GetRootUserEmail() (email string)

func GetUserEmail

func GetUserEmail(id int) (email string, err error)

func GetUserGroup

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

func GetUserLogsCount

func GetUserLogsCount(userId int, logType int, startTimestamp int64, endTimestamp int64, modelName string, tokenName string) (total int64, err error)

func GetUserQuota

func GetUserQuota(id int) (quota int64, err error)

func GetUserUsedQuota

func GetUserUsedQuota(id int) (quota int64, err error)

func GetUsernameById

func GetUsernameById(id int) (username string)

func IncreaseUserQuota

func IncreaseUserQuota(id int, quota int64) (err error)

func InitBatchUpdater

func InitBatchUpdater()

func InitChannelCache

func InitChannelCache()

func InitDB

func InitDB()

func InitLogDB

func InitLogDB()

func InitModelMetadataMap

func InitModelMetadataMap()

func InitOptionMap

func InitOptionMap()

func IsAdmin

func IsAdmin(userId int) bool

func IsEmailAlreadyTaken

func IsEmailAlreadyTaken(email string) bool

func IsMetadataExists

func IsMetadataExists(name string) bool

func IsUserEnabled

func IsUserEnabled(userId int) (bool, error)

func IsUsernameAlreadyTaken

func IsUsernameAlreadyTaken(username string) bool

func PostConsumeResetUserQuotaCache

func PostConsumeResetUserQuotaCache(ctx context.Context, userId int, consumedQuota int64)

PostConsumeResetUserQuotaCache refreshes the cached user quota from DB after the quota has already been updated in DB.

func RecordConsumeLog

func RecordConsumeLog(ctx context.Context, log *Log)

func RecordLog

func RecordLog(ctx context.Context, userId int, logType int, content string)

func RecordTestLog

func RecordTestLog(ctx context.Context, log *Log)

func RefreshModelMetadataMap

func RefreshModelMetadataMap()

func ResetUserPasswordByEmail

func ResetUserPasswordByEmail(email string, password string) error

func SimplifyModelName

func SimplifyModelName(modelName string) string

SimplifyModelName strips non-alphanumeric characters and lowercases the model name. This produces a simplified alias suitable for display or matching purposes.

func SimplifyModelsField

func SimplifyModelsField(models *string) *string

func SumUsedQuota

func SumUsedQuota(logType int, startTimestamp int64, endTimestamp int64, modelName string, username string, tokenName string, channel int) (quota int64)

func SumUsedToken

func SumUsedToken(logType int, startTimestamp int64, endTimestamp int64, modelName string, username string, tokenName string) (token int)

func SumUserQuotaTotal

func SumUserQuotaTotal(userId int) (token int)

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 UpdateAbilityStatus(channelId int, status bool) error

func UpdateChannelStatusById

func UpdateChannelStatusById(id int, status int)

func UpdateChannelUsedQuota

func UpdateChannelUsedQuota(id int, quota int64)

func UpdateModelMetadata

func UpdateModelMetadata(metadata *ModelMetadata) error

func UpdateOption

func UpdateOption(key string, value string) error

func UpdateUserUsedQuotaAndRequestCount

func UpdateUserUsedQuotaAndRequestCount(id int, quota int64)

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 CacheGetGroupChannels(group string) []*Channel

func CacheGetRandomSatisfiedChannel

func CacheGetRandomSatisfiedChannel(group string, model string, ignoreFirstPriority bool) (*Channel, error)

func GetAllChannels

func GetAllChannels(startIdx int, num int, scope string) ([]*Channel, error)

func GetChannelById

func GetChannelById(id int, selectAll bool) (*Channel, error)

func GetChannelsByGroup

func GetChannelsByGroup(group string) ([]*Channel, error)

func GetRandomSatisfiedChannel

func GetRandomSatisfiedChannel(group string, model string, ignoreFirstPriority bool) (*Channel, error)

func SearchChannels

func SearchChannels(keyword string) (channels []*Channel, err error)

func (*Channel) AddAbilities

func (channel *Channel) AddAbilities() error

func (*Channel) Delete

func (channel *Channel) Delete() error

func (*Channel) DeleteAbilities

func (channel *Channel) DeleteAbilities() error

func (*Channel) GetAlias

func (channel *Channel) GetAlias() []string

func (*Channel) GetBaseURL

func (channel *Channel) GetBaseURL() string

func (*Channel) GetModelMapping

func (channel *Channel) GetModelMapping() map[string]string

func (*Channel) GetModels

func (channel *Channel) GetModels() []string

func (*Channel) GetPriority

func (channel *Channel) GetPriority() int64

func (*Channel) Insert

func (channel *Channel) Insert() error

func (*Channel) LoadConfig

func (channel *Channel) LoadConfig() (ChannelConfig, error)

func (*Channel) Update

func (channel *Channel) Update() error

func (*Channel) UpdateAbilities

func (channel *Channel) UpdateAbilities() error

UpdateAbilities updates abilities of this channel. Make sure the channel is completed before calling this function.

func (*Channel) UpdateBalance

func (channel *Channel) UpdateBalance(balance float64)

func (*Channel) UpdateResponseTime

func (channel *Channel) UpdateResponseTime(responseTime int64)

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

func GetLogById(id int) (*Log, error)

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 GetAllLogs(logType int, startTimestamp int64, endTimestamp int64, modelName string, username string, tokenName string, startIdx int, num int, channel int) (logs []*LogListItem, err error)

func GetUserLogs

func GetUserLogs(userId int, logType int, startTimestamp int64, endTimestamp int64, modelName string, tokenName string, startIdx int, num int) (logs []*LogListItem, err error)

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 Option

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

func AllOption

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

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 CacheGetTokenByKey(key string) (*Token, error)

func GetAllUserTokens

func GetAllUserTokens(userId int, startIdx int, num int) ([]*Token, error)

func GetTokenById

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

func GetTokenByIds

func GetTokenByIds(id int, userId int) (*Token, error)

func SearchUserTokens

func SearchUserTokens(userId int, keyword string) (tokens []*Token, err error)

func ValidateUserToken

func ValidateUserToken(key string) (token *Token, err error)

func (*Token) Delete

func (t *Token) Delete() error

func (*Token) GetModelMapping

func (t *Token) GetModelMapping() map[string]string

func (*Token) GetModels

func (t *Token) GetModels() string

func (*Token) Insert

func (t *Token) Insert() error

func (*Token) Update

func (t *Token) Update() error

Update Make sure your token's fields is completed, because this will update non-zero values

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 GetAllUsers

func GetAllUsers(startIdx int, num int) (users []*User, err error)

func GetUserById

func GetUserById(id int, selectAll bool) (*User, error)

func SearchUsers

func SearchUsers(keyword string) (users []*User, err error)

func ValidateAccessToken

func ValidateAccessToken(token string) (user *User)

func (*User) Delete deprecated

func (user *User) Delete() error

Deprecated: user deletion is no longer supported after removing operational features.

func (*User) FillUserByEmail

func (user *User) FillUserByEmail() error

func (*User) FillUserById

func (user *User) FillUserById() error

func (*User) FillUserByUsername

func (user *User) FillUserByUsername() error

func (*User) Insert

func (user *User) Insert(ctx context.Context) error

func (*User) Update

func (user *User) Update(updatePassword bool) error

func (*User) ValidateAndFill

func (user *User) ValidateAndFill() (err error)

ValidateAndFill check password & user status

Jump to

Keyboard shortcuts

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