model

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Sep 19, 2026 License: MIT Imports: 31 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
	UserId2QuotaCacheSeconds  = config.SyncFrequency
	UserId2StatusCacheSeconds = config.SyncFrequency
	GroupModelsCacheSeconds   = config.SyncFrequency
)
View Source
var DB *gorm.DB
View Source
var LOG_DB *gorm.DB

Functions

func AddGroup added in v1.0.1

func AddGroup(group *Group) error

func BatchInsertChannels

func BatchInsertChannels(channels []Channel) error

func CacheDecreaseUserQuota

func CacheDecreaseUserQuota(id int, quota int64) error

CacheDecreaseUserQuota 对缓存额度做增量扣减(预扣/扣费路径调用),仅键存在时生效

func CacheGetGroupModels

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

func CacheGetUserQuota

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

func CacheIncreaseUserQuota added in v1.0.1

func CacheIncreaseUserQuota(id int, quota int64) error

CacheIncreaseUserQuota 对缓存额度做增量退回(回滚/退款路径调用),仅键存在时生效

func CacheInvalidateTokenByKey added in v1.0.1

func CacheInvalidateTokenByKey(key string) error

CacheInvalidateTokenByKey 在令牌写路径成功后失效 token:<key> 缓存, 消除"删除/禁用后旧凭证在 TTL 窗口内仍可调用"的安全窗口。 删除缓存失败仅记日志不回滚业务:缓存最终一致可接受, 最坏情况退化为既有 TTL 窗口,业务数据(DB)始终是权威状态。

func CacheInvalidateUserEnabled added in v1.0.1

func CacheInvalidateUserEnabled(userId int) error

CacheInvalidateUserEnabled 在用户状态写路径成功后失效 user_enabled:<id> 缓存。 调用方无法预判本次 Update 是否变更了 status,故统一失效, 代价仅为低频管理操作后的一次缓存回源。

func CacheIsUserEnabled

func CacheIsUserEnabled(userId int) (bool, error)

func CacheUpdateUserQuota

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

CacheUpdateUserQuota 以"读 DB(叠加差值) → SET 回写"覆盖缓存绝对值,该读改写并非原子, 与并发增量 Lua 脚本(DecreaseUserQuota 预扣 / IncreaseUserQuota 退回的 cacheIncrUserQuota)交织时: T1 读到旧值后 T2 的增量先落盘,再被 T1 的 SET 覆盖,T2 的增量丢失—— T2 为扣减则缓存高估一个预扣额(有界透支),T2 为退回则缓存低估(保守拒绝)。 窗口为读(含一次 DB 查询,远程 DB 下可达毫秒级)与 SET 之间的间隙,且有自愈路径:后续 PostConsumeReset 回写、 下次 CacheGetUserQuota 回源、TTL 过期均会重建真实值,不会持久漂移, 故接受该有界窗口而不引入分布式锁开销。

func CanonicalizeSimplifiedName added in v1.0.1

func CanonicalizeSimplifiedName(simplifiedName string) string

CanonicalizeSimplifiedName 将简化名归一化为等价组主名的简化名;未配置等价关系时原样返回。

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 DeleteGroup added in v1.0.1

func DeleteGroup(id int) 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 EnsureModelMetadataMapLoaded added in v1.0.1

func EnsureModelMetadataMapLoaded()

EnsureModelMetadataMapLoaded 保证内存索引至少从 DB 加载过一次;若标志位为 false 则触发 RefreshModelMetadataMap。配合包级 metadataMapOnce 保证高并发下只刷一次。

已知边界(可接受):metadataMapOnce 一旦被消费,若首次 RefreshModelMetadataMap 失败(DB 抖动), 标志位保持 false,后续 EnsureModelMetadataMapLoaded 因 Once 已 done 不会再尝试刷新—— 等价归一化会持续失效,直到下一次手动 Create/Update/Delete 路径直接调用 RefreshModelMetadataMap(不走 Once)成功恢复。GetModelMetadata/GetAllModelMetadata 等 直接打 DB 的接口不受影响,仅依赖内存索引的 CanonicalizeSimplifiedName 路由归并会失效。 该退化窗口用户可观测(路由不一致)但不会损坏数据;引入复杂重试机制得不偿失,故保留现状。 注意:minor-3 修复后 RefreshModelMetadataMap 在 DB 失败时不会把已为 true 的标志位置回 false, 因此正常启动场景下标志位已 true 的用例进 EnsureModelMetadataMapLoaded 走 IsCanonicalAliasMapLoaded 短路分支、不会触发 Once.Do,注释与最终实现一致。

func GetAllLogsCount

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

func GetGroupModelRatio added in v1.0.1

func GetGroupModelRatio(group string) float64

GetGroupModelRatio 返回指定组的倍率乘数。 default 组始终返回 1.0;其他组返回 DB 中存储的 ModelRatio(最小 0.001)。

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 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 GroupCount added in v1.0.1

func GroupCount() (int64, error)

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 IsCanonicalAliasMapLoaded added in v1.0.1

func IsCanonicalAliasMapLoaded() bool

IsCanonicalAliasMapLoaded 返回内存索引(modelMetadataMap / canonicalAliasMap)是否已经从 DB 完整重建过。该标志位由 InitModelMetadataMap / RefreshModelMetadataMap 在 DB 查询与 map 重建成功后置 true;查询失败时保持 false。仅读接口据此判断是否需要触发懒加载 Refresh。 注意:与"len(canonicalAliasMap) > 0"语义不同——部署无等价配置时 alias map 为空但索引仍可视为已加载。

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 ModelMetadataExistsBySimplifiedName added in v1.0.1

func ModelMetadataExistsBySimplifiedName(simplifiedName string) (bool, error)

ModelMetadataExistsBySimplifiedName 判断 DB 中是否存在原始 Name 经 SimplifyModelName 简化后等于 simplifiedName 的记录;用于 CreateMetadata 唯一性兜底(内存 map 未加载/被旁路时)。 实现策略:model_metadata 表本身体量很小(用户维护的模型元数据),全量 Find 后在 Go 侧 用 SimplifyModelName 做精确比对。原先依赖 LIKE 子序列粗筛的实现在 PostgreSQL 上区分 大小写(DB 保留原始 Name),与 MySQL/SQLite 默认 ci collation 不一致,PG 下当 DB 已存 "DeepSeek-V4-Flash" 时再以 "deepseek-v4-flash" 创建会绕过兜底允许重复,故改为跨方言稳定的全量比对。 查询失败时返回 error 以便调用方决定是拒绝创建还是放行,不再吞错。

func PostConsumeResetUserQuotaCache

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

PostConsumeResetUserQuotaCache 在 DB 扣费完成后刷新用户额度缓存。 批量模式下 DB 值尚未落盘,CacheUpdateUserQuota 会叠加批量缓冲差值后回写, 避免用陈旧 DB 值覆盖缓存(见 getPendingUserQuotaDelta); 非批量模式 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 ResetCanonicalAliasForTest added in v1.0.1

func ResetCanonicalAliasForTest()

ResetCanonicalAliasForTest 清空测试预置的等价映射,避免用例间污染。

func ResetModelMetadataMapForTest added in v1.0.1

func ResetModelMetadataMapForTest()

ResetModelMetadataMapForTest 重置全部包级元数据缓存(索引 + alias + 加载标志 + Once)。 仅供测试在用例入口/出口调用,保证用例间互不污染、单独运行也能稳定通过。

func ResetUserPasswordByEmail

func ResetUserPasswordByEmail(email string, password string) error

func SetCanonicalAliasForTest added in v1.0.1

func SetCanonicalAliasForTest(simplifiedName, canonicalSimplified string)

SetCanonicalAliasForTest 仅供测试预置等价映射,生产代码禁止调用。

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 UpdateGroup added in v1.0.1

func UpdateGroup(group *Group) error

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 Group added in v1.0.1

type Group struct {
	Id          int     `json:"id"`
	Name        string  `json:"name" gorm:"type:varchar(32);uniqueIndex"`
	ModelRatio  float64 `json:"model_ratio" gorm:"type:decimal(10,4);default:1.0"`
	CreatedTime int64   `json:"created_time" gorm:"bigint"`
}

Group 表示一个分组,每个分组有一个 float64 倍率作为全局 ModelRatio 的乘数。 default 组倍率为 1.0(完全向后兼容)。

func GetAllGroups added in v1.0.1

func GetAllGroups() ([]*Group, error)

func GetGroupById added in v1.0.1

func GetGroupById(id int) (*Group, error)

func GetGroupByName added in v1.0.1

func GetGroupByName(name string) (*Group, error)

func GetGroupList added in v1.0.1

func GetGroupList(page int, perPage int) (groups []*Group, total int64, err error)

func (*Group) TableName added in v1.0.1

func (g *Group) TableName() string

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
	FirstTokenTime    int64  `json:"first_token_time" gorm:"default:0"` // 首字耗时(TTFT),unit is ms;仅流式请求有值,非流式为 0
	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"`
	FirstTokenTime    int64  `json:"first_token_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, username string) (LogStatistics []*LogStatistic, err error)

type ModelMetadata

type ModelMetadata struct {
	Name                     string                 `json:"name" gorm:"primaryKey"`
	CanonicalName            string                 `json:"canonical_name" gorm:"default:''"`
	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;serializer:json"`
	ContextWindow            int                    `json:"context_window"`
	TruncationPolicy         string                 `json:"truncation_policy"`
	InputModalities          []string               `json:"input_modalities" gorm:"type:text;serializer:json"`
	OutputModalities         []string               `json:"output_modalities" gorm:"type:text;serializer:json"`
	SupportedEndpointTypes   []apitype.EndpointType `json:"supported_endpoint_types" gorm:"type:text;serializer:json"`
	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:''"`
	Group        string  `json:"group" gorm:"type:varchar(32);default:'default'"` // token belongs to a single group
}

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
}

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, columns ...string) error

Update 按显式列白名单写入。GORM struct Updates 会静默忽略零值字段,导致管理员把 quota 改为 0、清空 display_name 等操作失效,故改为 Select 白名单:选中列的零值也会落库。 password 不由调用方传入白名单,仅当 updatePassword 为 true 时自动写入(避免空串清空密码); username 为空串时跳过写入,避免把登录名清空(保持原先零值被忽略时的保护语义)。 各调用方白名单:UpdateUser(username/display_name/role/status,quota 仅在请求显式携带时附加, 见 controller 的 updateUserRequest)、UpdateSelf(username/display_name)、ManageUser(status)、 GenerateAccessToken(access_token)——UpdateSelf 等非管理员路径的敏感列 (role/quota/status/email 等)不进白名单,权限保护不再依赖"零值被忽略"的副作用。

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