✨ feat: refactor environment variable initialization - #1326
Conversation
…w constant types for API and context keys
WalkthroughThis change refactors the handling of channel and API type constants by moving their definitions from the Changes
Sequence Diagram(s)sequenceDiagram
participant Controller
participant Common
participant Constant
participant Model
participant GinContext
Controller->>Common: SetContextKey(c, key, value)
Common->>GinContext: Set(key.String(), value)
Controller->>Common: GetContextKeyString(c, key)
Common->>GinContext: GetString(key.String())
Controller->>Model: GetPricing()
Model->>Model: updatePricing()
Model->>Constant: Use ChannelType/APIType/EndpointType constants
Controller->>Common: ChannelType2APIType(channelType)
Common->>Constant: Use APIType constants
Controller->>Common: GetEndpointTypesByChannelType(channelType, modelName)
Common->>Constant: Use EndpointType constants
Possibly related PRs
Poem
✨ Finishing Touches
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (8)
types/set.go (3)
3-5: Consider thread safety requirements.This Set implementation is not thread-safe. If concurrent access is expected, consider adding mutex protection or documenting the thread safety requirements.
36-42: Optimize slice pre-allocation in Items() method.The current implementation pre-allocates with capacity 0, then uses the exact length. This is inefficient as it requires reallocation.
Apply this diff to optimize memory allocation:
- items := make([]T, 0, s.Len()) + items := make([]T, 0, len(s.items))Or even better, allocate with exact length:
-func (s *Set[T]) Items() []T { - items := make([]T, 0, s.Len()) - for item := range s.items { - items = append(items, item) - } - return items -} +func (s *Set[T]) Items() []T { + items := make([]T, 0, len(s.items)) + for item := range s.items { + items = append(items, item) + } + return items +}
7-7: Standardize comment language.Consider using consistent language for all comments (either English or Chinese) to improve maintainability for international teams.
Also applies to: 18-18
relay/relay_adaptor.go (1)
4-5: Clean up redundant import aliases.Having both
constantandcommonconstantaliases for the same package (one-api/constant) creates confusion and is unnecessary.Apply this diff to simplify the imports:
- "one-api/constant" - commonconstant "one-api/constant" + "one-api/constant"Then update the usage in
GetTaskAdaptorfunction:-func GetTaskAdaptor(platform commonconstant.TaskPlatform) channel.TaskAdaptor { +func GetTaskAdaptor(platform constant.TaskPlatform) channel.TaskAdaptor {And update the case statements:
- case commonconstant.TaskPlatformSuno: - case commonconstant.TaskPlatformKling: - case commonconstant.TaskPlatformJimeng: + case constant.TaskPlatformSuno: + case constant.TaskPlatformKling: + case constant.TaskPlatformJimeng:constant/context_key.go (1)
27-27: Consider using more specific context key values to avoid collisions.The context key values
"id","group", and"username"are very generic and could potentially collide with other uses of these strings in the codebase. Consider using more descriptive values to ensure uniqueness.- ContextKeyUserId ContextKey = "id" + ContextKeyUserId ContextKey = "user_id"- ContextKeyUsingGroup ContextKey = "group" + ContextKeyUsingGroup ContextKey = "using_group"- ContextKeyUserName ContextKey = "username" + ContextKeyUserName ContextKey = "user_name"Also applies to: 33-35
model/pricing.go (2)
79-79: Translate comment to English for consistency.Please translate the Chinese comment to English to maintain consistency across the codebase.
- //这里使用切片而不是Set,因为一个模型可能支持多个端点类型,并且第一个端点是优先使用端点 + // Use slice instead of Set here because a model may support multiple endpoint types, and the first endpoint is the preferred one
88-95: Consider using a map for O(1) duplicate checking.The current implementation uses
common.StringsContainswhich performs a linear search. For better performance with large datasets, consider using a map for O(1) lookups.for _, ability := range enableAbilities { - endpoints, ok := modelSupportEndpointsStr[ability.Model] - if !ok { - endpoints = make([]string, 0) - modelSupportEndpointsStr[ability.Model] = endpoints - } + if _, ok := modelSupportEndpointsStr[ability.Model]; !ok { + modelSupportEndpointsStr[ability.Model] = make([]string, 0) + } + // Use a map to track seen endpoints for O(1) lookup + seenEndpoints := make(map[string]bool) + for _, endpoint := range modelSupportEndpointsStr[ability.Model] { + seenEndpoints[endpoint] = true + } channelTypes := common.GetEndpointTypesByChannelType(ability.ChannelType, ability.Model) for _, channelType := range channelTypes { - if !common.StringsContains(endpoints, string(channelType)) { - endpoints = append(endpoints, string(channelType)) + endpointStr := string(channelType) + if !seenEndpoints[endpointStr] { + modelSupportEndpointsStr[ability.Model] = append(modelSupportEndpointsStr[ability.Model], endpointStr) } } - modelSupportEndpointsStr[ability.Model] = endpoints }constant/channel.go (1)
4-54: Document the reason for gaps in channel type constants.There are gaps in the channel type numbering (28-30, 32). Please add comments explaining why these numbers are skipped to prevent confusion for future maintainers.
ChannelTypePerplexity = 27 + // 28-30 reserved for future use ChannelTypeLingYiWanWu = 31 + // 32 reserved for future use ChannelTypeAws = 33
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (43)
common/api_type.go(1 hunks)common/constants.go(0 hunks)common/endpoint_type.go(1 hunks)common/gin.go(2 hunks)common/init.go(3 hunks)common/model.go(1 hunks)common/redis.go(1 hunks)constant/README.md(1 hunks)constant/api_type.go(1 hunks)constant/cache_key.go(0 hunks)constant/channel.go(1 hunks)constant/context_key.go(1 hunks)constant/endpoint_type.go(1 hunks)constant/env.go(0 hunks)controller/channel-billing.go(2 hunks)controller/channel-test.go(4 hunks)controller/channel.go(7 hunks)controller/model.go(4 hunks)controller/playground.go(1 hunks)controller/relay.go(4 hunks)controller/task_video.go(1 hunks)controller/user.go(1 hunks)dto/pricing.go(1 hunks)main.go(2 hunks)middleware/distributor.go(6 hunks)middleware/model-rate-limit.go(1 hunks)model/ability.go(3 hunks)model/pricing.go(2 hunks)model/token_cache.go(1 hunks)model/user_cache.go(2 hunks)relay/channel/openai/adaptor.go(14 hunks)relay/channel/openai/relay-openai.go(1 hunks)relay/common/relay_info.go(3 hunks)relay/common/relay_utils.go(2 hunks)relay/common_handler/rerank.go(2 hunks)relay/constant/api_type.go(0 hunks)relay/image_handler.go(1 hunks)relay/relay_adaptor.go(1 hunks)service/channel.go(2 hunks)service/convert.go(2 hunks)service/quota.go(3 hunks)service/token_counter.go(1 hunks)types/set.go(1 hunks)
💤 Files with no reviewable changes (4)
- common/constants.go
- constant/cache_key.go
- constant/env.go
- relay/constant/api_type.go
🧰 Additional context used
🧠 Learnings (11)
controller/relay.go (2)
Learnt from: feitianbubu
PR: QuantumNous/new-api#1228
File: router/main.go:28-36
Timestamp: 2025-06-15T12:38:11.806Z
Learning: gin.Context implements context.Context interface since Gin v1.8.0, providing the methods Deadline(), Done(), Err(), and Value(). When using Gin v1.8.0 or later, gin.Context can be passed directly to functions expecting context.Context without needing to extract c.Request.Context().
Learnt from: feitianbubu
PR: QuantumNous/new-api#1228
File: router/main.go:28-36
Timestamp: 2025-06-15T12:38:11.806Z
Learning: gin.Context implements context.Context interface since Gin v1.8.0, providing the methods Deadline(), Done(), Err(), and Value(). When using Gin v1.8.0 or later, gin.Context can be passed directly to functions expecting context.Context without needing to extract c.Request.Context().
controller/playground.go (2)
Learnt from: feitianbubu
PR: QuantumNous/new-api#1228
File: router/main.go:28-36
Timestamp: 2025-06-15T12:38:11.806Z
Learning: gin.Context implements context.Context interface since Gin v1.8.0, providing the methods Deadline(), Done(), Err(), and Value(). When using Gin v1.8.0 or later, gin.Context can be passed directly to functions expecting context.Context without needing to extract c.Request.Context().
Learnt from: feitianbubu
PR: QuantumNous/new-api#1228
File: router/main.go:28-36
Timestamp: 2025-06-15T12:38:11.806Z
Learning: gin.Context implements context.Context interface since Gin v1.8.0, providing the methods Deadline(), Done(), Err(), and Value(). When using Gin v1.8.0 or later, gin.Context can be passed directly to functions expecting context.Context without needing to extract c.Request.Context().
middleware/model-rate-limit.go (2)
Learnt from: feitianbubu
PR: QuantumNous/new-api#1228
File: router/main.go:28-36
Timestamp: 2025-06-15T12:38:11.806Z
Learning: gin.Context implements context.Context interface since Gin v1.8.0, providing the methods Deadline(), Done(), Err(), and Value(). When using Gin v1.8.0 or later, gin.Context can be passed directly to functions expecting context.Context without needing to extract c.Request.Context().
Learnt from: feitianbubu
PR: QuantumNous/new-api#1228
File: router/main.go:28-36
Timestamp: 2025-06-15T12:38:11.806Z
Learning: gin.Context implements context.Context interface since Gin v1.8.0, providing the methods Deadline(), Done(), Err(), and Value(). When using Gin v1.8.0 or later, gin.Context can be passed directly to functions expecting context.Context without needing to extract c.Request.Context().
middleware/distributor.go (2)
Learnt from: feitianbubu
PR: QuantumNous/new-api#1228
File: router/main.go:28-36
Timestamp: 2025-06-15T12:38:11.806Z
Learning: gin.Context implements context.Context interface since Gin v1.8.0, providing the methods Deadline(), Done(), Err(), and Value(). When using Gin v1.8.0 or later, gin.Context can be passed directly to functions expecting context.Context without needing to extract c.Request.Context().
Learnt from: feitianbubu
PR: QuantumNous/new-api#1228
File: router/main.go:28-36
Timestamp: 2025-06-15T12:38:11.806Z
Learning: gin.Context implements context.Context interface since Gin v1.8.0, providing the methods Deadline(), Done(), Err(), and Value(). When using Gin v1.8.0 or later, gin.Context can be passed directly to functions expecting context.Context without needing to extract c.Request.Context().
service/token_counter.go (1)
Learnt from: 9Ninety
PR: QuantumNous/new-api#1273
File: relay/channel/gemini/relay-gemini.go:97-116
Timestamp: 2025-06-21T03:37:41.726Z
Learning: In relay/channel/gemini/relay-gemini.go, the thinking budget calculation logic (including the MaxOutputTokens multiplication) was introduced in PR #1247. PR #1273 focused specifically on decoupling the thoughts summary feature from thinking budget settings and did not modify the existing thinking budget behavior.
service/quota.go (2)
Learnt from: neotf
PR: QuantumNous/new-api#1120
File: service/quota.go:0-0
Timestamp: 2025-06-18T12:20:25.779Z
Learning: For OpenRouter integration: cacheTokens returned from upstream always belong to [0, promptTokens], meaning cacheTokens will never exceed the original promptTokens value. This constraint ensures that operations like `promptTokens -= cacheTokens` will not result in negative values.
Learnt from: 9Ninety
PR: QuantumNous/new-api#1273
File: relay/channel/gemini/relay-gemini.go:97-116
Timestamp: 2025-06-21T03:37:41.726Z
Learning: In relay/channel/gemini/relay-gemini.go, the thinking budget calculation logic (including the MaxOutputTokens multiplication) was introduced in PR #1247. PR #1273 focused specifically on decoupling the thoughts summary feature from thinking budget settings and did not modify the existing thinking budget behavior.
model/user_cache.go (2)
Learnt from: feitianbubu
PR: QuantumNous/new-api#1228
File: router/main.go:28-36
Timestamp: 2025-06-15T12:38:11.806Z
Learning: gin.Context implements context.Context interface since Gin v1.8.0, providing the methods Deadline(), Done(), Err(), and Value(). When using Gin v1.8.0 or later, gin.Context can be passed directly to functions expecting context.Context without needing to extract c.Request.Context().
Learnt from: feitianbubu
PR: QuantumNous/new-api#1228
File: router/main.go:28-36
Timestamp: 2025-06-15T12:38:11.806Z
Learning: gin.Context implements context.Context interface since Gin v1.8.0, providing the methods Deadline(), Done(), Err(), and Value(). When using Gin v1.8.0 or later, gin.Context can be passed directly to functions expecting context.Context without needing to extract c.Request.Context().
constant/context_key.go (2)
Learnt from: feitianbubu
PR: QuantumNous/new-api#1228
File: router/main.go:28-36
Timestamp: 2025-06-15T12:38:11.806Z
Learning: gin.Context implements context.Context interface since Gin v1.8.0, providing the methods Deadline(), Done(), Err(), and Value(). When using Gin v1.8.0 or later, gin.Context can be passed directly to functions expecting context.Context without needing to extract c.Request.Context().
Learnt from: feitianbubu
PR: QuantumNous/new-api#1228
File: router/main.go:28-36
Timestamp: 2025-06-15T12:38:11.806Z
Learning: gin.Context implements context.Context interface since Gin v1.8.0, providing the methods Deadline(), Done(), Err(), and Value(). When using Gin v1.8.0 or later, gin.Context can be passed directly to functions expecting context.Context without needing to extract c.Request.Context().
relay/common/relay_info.go (2)
Learnt from: feitianbubu
PR: QuantumNous/new-api#1228
File: router/main.go:28-36
Timestamp: 2025-06-15T12:38:11.806Z
Learning: gin.Context implements context.Context interface since Gin v1.8.0, providing the methods Deadline(), Done(), Err(), and Value(). When using Gin v1.8.0 or later, gin.Context can be passed directly to functions expecting context.Context without needing to extract c.Request.Context().
Learnt from: feitianbubu
PR: QuantumNous/new-api#1228
File: router/main.go:28-36
Timestamp: 2025-06-15T12:38:11.806Z
Learning: gin.Context implements context.Context interface since Gin v1.8.0, providing the methods Deadline(), Done(), Err(), and Value(). When using Gin v1.8.0 or later, gin.Context can be passed directly to functions expecting context.Context without needing to extract c.Request.Context().
common/gin.go (2)
Learnt from: feitianbubu
PR: QuantumNous/new-api#1228
File: router/main.go:28-36
Timestamp: 2025-06-15T12:38:11.806Z
Learning: gin.Context implements context.Context interface since Gin v1.8.0, providing the methods Deadline(), Done(), Err(), and Value(). When using Gin v1.8.0 or later, gin.Context can be passed directly to functions expecting context.Context without needing to extract c.Request.Context().
Learnt from: feitianbubu
PR: QuantumNous/new-api#1228
File: router/main.go:28-36
Timestamp: 2025-06-15T12:38:11.806Z
Learning: gin.Context implements context.Context interface since Gin v1.8.0, providing the methods Deadline(), Done(), Err(), and Value(). When using Gin v1.8.0 or later, gin.Context can be passed directly to functions expecting context.Context without needing to extract c.Request.Context().
controller/model.go (2)
Learnt from: feitianbubu
PR: QuantumNous/new-api#1228
File: router/main.go:28-36
Timestamp: 2025-06-15T12:38:11.806Z
Learning: gin.Context implements context.Context interface since Gin v1.8.0, providing the methods Deadline(), Done(), Err(), and Value(). When using Gin v1.8.0 or later, gin.Context can be passed directly to functions expecting context.Context without needing to extract c.Request.Context().
Learnt from: feitianbubu
PR: QuantumNous/new-api#1228
File: router/main.go:28-36
Timestamp: 2025-06-15T12:38:11.806Z
Learning: gin.Context implements context.Context interface since Gin v1.8.0, providing the methods Deadline(), Done(), Err(), and Value(). When using Gin v1.8.0 or later, gin.Context can be passed directly to functions expecting context.Context without needing to extract c.Request.Context().
🧬 Code Graph Analysis (23)
controller/user.go (1)
model/ability.go (1)
GetGroupEnabledModels(39-44)
controller/relay.go (2)
relay/constant/relay_mode.go (1)
Path2RelayMode(56-90)constant/channel.go (1)
ChannelTypeAnthropic(18-18)
common/redis.go (1)
common/constants.go (1)
SyncFrequency(115-115)
controller/task_video.go (1)
constant/channel.go (1)
ChannelBaseURLs(56-109)
service/channel.go (1)
constant/channel.go (1)
ChannelTypeGemini(28-28)
controller/playground.go (2)
common/gin.go (1)
SetContextKey(48-50)constant/context_key.go (1)
ContextKeyRequestStartTime(7-7)
middleware/model-rate-limit.go (2)
common/gin.go (1)
GetContextKeyString(56-58)constant/context_key.go (2)
ContextKeyTokenGroup(13-13)ContextKeyUserGroup(32-32)
relay/common/relay_utils.go (1)
constant/channel.go (2)
ChannelTypeOpenAI(5-5)ChannelTypeAzure(7-7)
model/token_cache.go (1)
common/redis.go (2)
RedisHSetObj(107-159)RedisKeyCacheSeconds(19-21)
middleware/distributor.go (3)
common/gin.go (5)
GetContextKeyStringMap(72-74)GetContextKey(52-54)GetContextKeyString(56-58)SetContextKey(48-50)GetContextKeyBool(64-66)constant/context_key.go (8)
ContextKeyTokenAllowIps(14-14)ContextKeyTokenSpecificChannelId(15-15)ContextKeyUserGroup(32-32)ContextKeyTokenGroup(13-13)ContextKeyUsingGroup(33-33)ContextKeyTokenModelLimitEnabled(16-16)ContextKeyTokenModelLimit(17-17)ContextKeyRequestStartTime(7-7)constant/channel.go (8)
ChannelTypeAzure(7-7)ChannelTypeVertexAi(41-41)ChannelTypeXunfei(22-22)ChannelTypeGemini(28-28)ChannelTypeAli(21-21)ChannelCloudflare(39-39)ChannelTypeMokaAI(44-44)ChannelTypeCoze(49-49)
service/token_counter.go (1)
constant/channel.go (3)
ChannelTypeGemini(28-28)ChannelTypeVertexAi(41-41)ChannelTypeAnthropic(18-18)
relay/channel/openai/relay-openai.go (1)
constant/channel.go (1)
ChannelTypeDeepSeek(43-43)
service/quota.go (2)
constant/channel.go (1)
ChannelTypeOpenRouter(24-24)constant/user_setting.go (1)
UserSettingQuotaWarningThreshold(5-5)
model/user_cache.go (3)
common/gin.go (1)
SetContextKey(48-50)constant/context_key.go (6)
ContextKeyUserGroup(32-32)ContextKeyUserQuota(29-29)ContextKeyUserStatus(30-30)ContextKeyUserEmail(31-31)ContextKeyUserName(34-34)ContextKeyUserSetting(28-28)common/redis.go (1)
RedisKeyCacheSeconds(19-21)
service/convert.go (1)
constant/channel.go (1)
ChannelTypeOpenRouter(24-24)
controller/channel.go (1)
constant/channel.go (4)
ChannelBaseURLs(56-109)ChannelTypeGemini(28-28)ChannelTypeAli(21-21)ChannelTypeVertexAi(41-41)
dto/pricing.go (1)
constant/endpoint_type.go (1)
EndpointType(3-3)
controller/channel-billing.go (1)
constant/channel.go (11)
ChannelBaseURLs(56-109)ChannelTypeOpenAI(5-5)ChannelTypeAzure(7-7)ChannelTypeCustom(12-12)ChannelTypeAIProxy(14-14)ChannelTypeAPI2GPT(16-16)ChannelTypeAIGC2D(17-17)ChannelTypeSiliconFlow(40-40)ChannelTypeDeepSeek(43-43)ChannelTypeOpenRouter(24-24)ChannelTypeMoonshot(29-29)
relay/common_handler/rerank.go (1)
constant/channel.go (1)
ChannelTypeXinference(47-47)
common/api_type.go (2)
constant/channel.go (29)
ChannelTypeOpenAI(5-5)ChannelTypeAnthropic(18-18)ChannelTypeBaidu(19-19)ChannelTypePaLM(15-15)ChannelTypeZhipu(20-20)ChannelTypeAli(21-21)ChannelTypeXunfei(22-22)ChannelTypeAIProxyLibrary(25-25)ChannelTypeTencent(27-27)ChannelTypeGemini(28-28)ChannelTypeZhipu_v4(30-30)ChannelTypeOllama(8-8)ChannelTypePerplexity(31-31)ChannelTypeAws(33-33)ChannelTypeCohere(34-34)ChannelTypeDify(37-37)ChannelTypeJina(38-38)ChannelCloudflare(39-39)ChannelTypeSiliconFlow(40-40)ChannelTypeVertexAi(41-41)ChannelTypeMistral(42-42)ChannelTypeDeepSeek(43-43)ChannelTypeMokaAI(44-44)ChannelTypeVolcEngine(45-45)ChannelTypeBaiduV2(46-46)ChannelTypeOpenRouter(24-24)ChannelTypeXinference(47-47)ChannelTypeXai(48-48)ChannelTypeCoze(49-49)constant/api_type.go (29)
APITypeOpenAI(4-4)APITypeAnthropic(5-5)APITypeBaidu(7-7)APITypePaLM(6-6)APITypeZhipu(8-8)APITypeAli(9-9)APITypeXunfei(10-10)APITypeAIProxyLibrary(11-11)APITypeTencent(12-12)APITypeGemini(13-13)APITypeZhipuV4(14-14)APITypeOllama(15-15)APITypePerplexity(16-16)APITypeAws(17-17)APITypeCohere(18-18)APITypeDify(19-19)APITypeJina(20-20)APITypeCloudflare(21-21)APITypeSiliconFlow(22-22)APITypeVertexAi(23-23)APITypeMistral(24-24)APITypeDeepSeek(25-25)APITypeMokaAI(26-26)APITypeVolcEngine(27-27)APITypeBaiduV2(28-28)APITypeOpenRouter(29-29)APITypeXinference(30-30)APITypeXai(31-31)APITypeCoze(32-32)
common/endpoint_type.go (3)
constant/endpoint_type.go (6)
EndpointType(3-3)EndpointTypeJinaRerank(10-10)EndpointTypeAnthropic(8-8)EndpointTypeOpenAI(6-6)EndpointTypeGemini(9-9)EndpointTypeOpenAIResponse(7-7)constant/channel.go (6)
ChannelTypeJina(38-38)ChannelTypeAws(33-33)ChannelTypeAnthropic(18-18)ChannelTypeVertexAi(41-41)ChannelTypeGemini(28-28)ChannelTypeOpenRouter(24-24)common/model.go (1)
IsOpenAIResponseOnlyModel(14-21)
common/init.go (2)
constant/env.go (13)
StreamingTimeout(3-3)DifyDebug(4-4)MaxFileDownloadMB(5-5)ForceStreamOption(6-6)GetMediaToken(7-7)GetMediaTokenNotStream(8-8)UpdateTask(9-9)AzureDefaultAPIVersion(10-10)GeminiVisionMaxImageNum(11-11)NotifyLimitCount(12-12)NotificationLimitDurationMinute(13-13)GenerateDefaultToken(14-14)ErrorLogEnabled(15-15)common/env.go (3)
GetEnvOrDefault(9-19)GetEnvOrDefaultBool(28-38)GetEnvOrDefaultString(21-26)
common/gin.go (1)
constant/context_key.go (1)
ContextKey(3-3)
🔇 Additional comments (71)
relay/image_handler.go (1)
11-11: LGTM! Import refactoring aligns with constant centralization.The import change from
relay/constanttoconstantis consistent with the broader refactoring to centralize constant definitions.service/channel.go (1)
7-7: LGTM! Constant reference updated correctly.The import addition and constant reference change from
common.ChannelTypeGeminitoconstant.ChannelTypeGeminialigns with the centralization of channel type constants.Also applies to: 52-52
relay/channel/openai/relay-openai.go (1)
171-171: LGTM! Constant reference updated correctly.The change from
common.ChannelTypeDeepSeektoconstant.ChannelTypeDeepSeekis consistent with the refactoring to centralize channel type constants.service/convert.go (1)
7-7: LGTM! Clean refactoring to centralize constants.The import addition and constant reference update correctly aligns with the broader refactoring effort to move channel type constants from the
commonpackage to theconstantpackage. The logic remains unchanged and the constant is properly defined inconstant/channel.go.Also applies to: 23-23
common/redis.go (1)
19-21: LGTM! Well-placed utility function.The new
RedisKeyCacheSeconds()function provides a clean interface for accessing the cache duration. Moving this from theconstantpackage to thecommonpackage is appropriate since it deals with runtime configuration rather than static constants.relay/common_handler/rerank.go (1)
8-8: LGTM! Consistent with the constant centralization effort.The import addition and constant reference update are part of the systematic refactoring to move channel type constants to the
constantpackage. The logic remains unchanged and the constant is properly defined inconstant/channel.go.Also applies to: 25-25
relay/common/relay_utils.go (1)
9-9: LGTM! Consistent refactoring maintains functionality.The import update and constant reference changes align with the systematic effort to centralize channel type constants. The
GetFullRequestURLfunction logic remains unchanged and both constants are properly defined inconstant/channel.go.Also applies to: 18-18, 20-20
service/token_counter.go (1)
104-104: LGTM! Refactoring preserves token calculation logic.The constant reference update from
commontoconstantpackage maintains the exact same conditional logic for image token calculation. All three channel type constants are properly defined inconstant/channel.goand the token calculation behavior remains unchanged.controller/channel-billing.go (1)
11-11: LGTM! Clean namespace refactoring for channel constants.The systematic migration of channel type constants and base URLs from the
commonpackage to theconstantpackage is well-executed. All references are consistently updated and the import statement is properly added.Also applies to: 345-345, 350-372
controller/playground.go (1)
68-68: LGTM! Improved type safety with context key helper function.The change from direct
c.Set()tocommon.SetContextKey()with a typed constant improves type safety and aligns with the standardized context key management approach introduced in this refactoring.controller/task_video.go (1)
54-54: LGTM! Consistent namespace migration for ChannelBaseURLs.The change from
common.ChannelBaseURLstoconstant.ChannelBaseURLsis consistent with the broader refactoring effort to move channel-related constants to theconstantpackage.model/token_cache.go (1)
13-13: LGTM! Correct placement of configuration function in common package.The change from
constant.RedisKeyCacheSeconds()tocommon.RedisKeyCacheSeconds()correctly moves this environment/configuration-related function to thecommonpackage where it belongs, while keeping type constants in theconstantpackage.middleware/model-rate-limit.go (1)
180-183: LGTM! Excellent improvement in type safety for context key access.The changes replace direct
c.GetString()calls withcommon.GetContextKeyString()helper function and typed constants. This eliminates magic strings, improves type safety, and standardizes context key access patterns across the codebase.controller/user.go (1)
490-490: LGTM! Improved filtering logic.The change from
GetGroupModelstoGetGroupEnabledModelscorrectly filters for only enabled models, which is more appropriate for determining user-available models.main.go (2)
173-173: LGTM! Environment initialization consolidated.The consolidation of environment variable initialization into a single
common.InitEnv()call improves code organization and reduces duplication.
194-195: LGTM! Logical placement of pricing initialization.Adding
model.GetPricing()aftermodel.InitOptionMap()and before database initialization ensures pricing data is available early in the initialization sequence.controller/relay.go (4)
11-11: LGTM! Import added for constant package.Adding the import for the
constantpackage aligns with the refactoring to centralize constants.
17-17: LGTM! Import alias prevents naming conflicts.Using
relayconstantas an alias for the relay constant package prevents naming conflicts with the globalconstantpackage.
72-72: LGTM! Consistent use of updated import alias.The function calls are correctly updated to use the
relayconstantalias, maintaining consistency throughout the file.Also applies to: 135-135
298-298: LGTM! Channel type constant moved to constant package.The change from
common.ChannelTypeAnthropictoconstant.ChannelTypeAnthropicaligns with the refactoring to centralize channel type constants in theconstantpackage.constant/endpoint_type.go (1)
1-11: LGTM! Well-designed type definition.The new
EndpointTypeas a custom string type provides type safety while remaining readable. The constant definitions are descriptive and follow Go naming conventions.model/user_cache.go (2)
27-32: LGTM! Improved type safety with typed constants.The change from direct
c.Set()calls tocommon.SetContextKey()with typedconstant.ContextKeyconstants improves type safety and consistency across the codebase.
73-73: LGTM! Function relocated to appropriate package.The change from
constant.RedisKeyCacheSeconds()tocommon.RedisKeyCacheSeconds()aligns with the package reorganization, moving cache-related utilities to thecommonpackage.relay/channel/openai/adaptor.go (2)
12-12: LGTM! Clean import organization for constants refactoring.The import changes properly separate channel constants (
constant) from relay constants (relayconstant) as part of the broader constants reorganization.Also applies to: 23-23
56-56: Consistent constants migration successfully implemented.All constant references have been properly updated from the
commonpackage to the appropriate new locations (constantfor channel types andrelayconstantfor relay modes). The refactoring maintains all existing functionality while improving code organization.Also applies to: 69-69, 81-81, 84-84, 92-92, 99-99, 104-104, 108-108, 110-110, 121-121, 125-125, 128-128, 147-147, 158-161, 207-207, 256-256, 413-417, 426-439, 456-467
dto/pricing.go (2)
3-3: LGTM! Import aligns with constants refactoring.The import of the
constantpackage is consistent with the broader effort to centralize constants and type definitions.
6-11: Approve the model metadata modernization.The replacement of static permission fields with
SupportedEndpointTypesprovides a more flexible and dynamic approach to representing model capabilities. This change aligns well with the endpoint type system introduced in theconstantpackage.common/model.go (2)
5-12: LGTM! Clear model categorization with good documentation.The
OpenAIResponseOnlyModelslist provides clear categorization of models with specific usage restrictions. The variable naming and documentation are clear and descriptive.
14-21: Review the substring matching logic for correctness.The current logic
strings.Contains(m, modelName)checks ifmodelNameis contained within each predefined modelm. This may not match the intended behavior:
- Current: checks if input is a substring of predefined models
- Expected: likely should check if predefined models match or are contained in the input
Consider whether the matching logic should be:
- for _, m := range OpenAIResponseOnlyModels { - if strings.Contains(m, modelName) { - return true - } - } + for _, m := range OpenAIResponseOnlyModels { + if strings.Contains(modelName, m) || m == modelName { + return true + } + }Please verify the intended matching behavior for this function.
service/quota.go (2)
9-9: LGTM! Import cleanup aligns with constants refactoring.The removal of the
constant2alias and direct import ofconstantpackage simplifies the import structure and aligns with the broader constants reorganization.
235-235: Consistent constant references properly updated.Both constant references have been correctly updated to use the new
constantpackage namespace:
constant.ChannelTypeOpenRouter(line 235)constant.UserSettingQuotaWarningThreshold(line 450)The changes maintain existing functionality while improving code organization.
Also applies to: 450-450
middleware/distributor.go (2)
28-28: Excellent type safety improvement with typed context keys.The replacement of direct Gin context methods with typed wrapper functions significantly improves type safety:
- Eliminates string literal errors in context key usage
- Provides consistent interface for context access
- Uses strongly typed
constant.ContextKeyconstantsThis refactoring reduces the likelihood of runtime errors from typos in context key strings.
Also applies to: 37-37, 43-44, 60-60, 79-79, 81-81, 124-124
264-279: Channel type constants properly migrated.All channel type references have been correctly updated to use the
constantpackage namespace, maintaining consistency with the broader constants refactoring effort across the codebase.controller/channel.go (7)
8-8: LGTM: Import addition aligns with constant package refactoring.The addition of the constant package import is necessary for the updated constant references throughout the file.
129-129: LGTM: Minor formatting improvement.The spacing adjustment improves code readability.
185-185: LGTM: Constant reference updated correctly.The change from
common.ChannelBaseURLstoconstant.ChannelBaseURLsis consistent with the constant package refactoring.
191-195: LGTM: Channel type constants updated consistently.All channel type references have been correctly updated to use the
constantpackage namespace.
217-217: LGTM: Consistent channel type constant usage.The update maintains consistency with other channel type constant changes in the file.
392-392: LGTM: VertexAi channel type references updated.Both instances of
ChannelTypeVertexAihave been correctly updated to use the constant package.Also applies to: 617-617
672-672: LGTM: Base URLs reference updated consistently.The final reference to
ChannelBaseURLshas been updated to maintain consistency throughout the file.common/init.go (4)
7-7: LGTM: Import addition supports constant package initialization.The constant package import is necessary for the new
initConstantEnvfunction.
28-28: LGTM: Function rename improves clarity.Renaming from
InitCommonEnvtoInitEnvbetter reflects the function's broader scope of initializing environment variables across packages.
100-101: LGTM: Modular initialization approach.Calling
initConstantEnv()at the end ofInitEnv()provides a clean separation of concerns for initializing different package variables.
103-120: LGTM: Comprehensive constant environment initialization.The
initConstantEnvfunction properly initializes all constant package variables using the existing helper functions with appropriate defaults. The comments provide helpful context for specific variables.controller/channel-test.go (5)
14-14: LGTM: Import addition supports updated constant references.The constant package import is required for the channel type constant updates throughout the file.
34-48: LGTM: Channel type constants updated consistently.All channel type references have been correctly updated to use the
constantpackage namespace, maintaining consistency with the refactoring effort.
38-38: LGTM: Error message formatting improvement.Removing the extra exclamation mark makes the error message more professional and consistent.
59-59: LGTM: Consistent constant usage in conditional.The update to
constant.ChannelTypeMokaAImaintains consistency with other channel type constant changes.
105-105: LGTM: Correct usage of relocated mapping function.Using
common.ChannelType2APITypeis correct since this function was moved to the common package as part of the refactoring.common/api_type.go (4)
1-4: LGTM: Clean package structure and import.The package declaration and constant import are appropriate for this utility function.
5-6: LGTM: Well-designed function signature.The function signature with boolean return value allows callers to distinguish between valid mappings and fallback cases.
7-66: LGTM: Comprehensive channel type to API type mapping.The switch statement covers all major channel types and maps them to their corresponding API types correctly based on the constant definitions.
67-71: LGTM: Appropriate fallback behavior.Returning
APITypeOpenAIas the default withfalsesuccess flag provides a safe fallback while allowing callers to detect unmapped channel types.common/endpoint_type.go (4)
1-4: LGTM: Appropriate package structure.Clean package declaration and necessary import for constant definitions.
5-6: LGTM: Well-documented function signature.The comment clearly explains the function's purpose and that all channels support OpenAI endpoints. The function signature appropriately takes both channel type and model name for context-aware decisions.
8-20: LGTM: Logical endpoint type mappings with priority ordering.The mappings are logical:
- Jina channels prioritize their rerank endpoint
- Anthropic/AWS channels support both native and OpenAI endpoints
- Gemini/VertexAI channels support both native and OpenAI endpoints
- OpenRouter only supports OpenAI endpoints
The use of
fallthroughfor AWS→Anthropic and VertexAI→Gemini is appropriate since they share the same endpoint support.
21-28: LGTM: Intelligent fallback logic.The default case uses model-specific logic to determine endpoint type, which provides more granular control than a simple channel-based approach. This allows for model-specific optimizations while maintaining a sensible fallback.
constant/README.md (1)
1-26: Excellent documentation for the constant package.The README provides comprehensive documentation with clear purpose, file descriptions, and usage conventions. The restrictions are well-defined and will help maintain clean architecture by preventing unwanted dependencies and coupling.
relay/common/relay_info.go (4)
116-126: LGTM: Consistent migration to constant package.The update of
streamSupportedChannelsmap to use constants from theconstantpackage is consistent with the broader refactoring effort to centralize constant definitions.
214-247: Excellent improvement: Type-safe context key access.The migration from raw string keys to typed context helper functions (e.g.,
common.GetContextKeyInt(c, constant.ContextKeyChannelType)) provides better type safety and consistency. This aligns well with the new typedconstant.ContextKeyapproach.
226-226: LGTM: Updated API type conversion.The use of
common.ChannelType2APIType(channelType)is consistent with the refactoring that moved API type mapping logic to thecommonpackage.
269-275: Consistent constant package usage.The updates to use
constant.ChannelBaseURLs,constant.ChannelTypeAzure, andconstant.ChannelTypeVertexAiare consistent with the constant centralization effort.model/ability.go (4)
24-27: Good design: Extended struct for ability-channel relationship.The
AbilityWithChannelstruct that embedsAbilityand addsChannelTypeis a clean way to represent the joined data without modifying the baseAbilitystruct.
29-37: Well-implemented JOIN query.The
GetAllEnableAbilityWithChannelsfunction properly uses a LEFT JOIN to combine abilities with channel types. The query structure is correct and the error handling is appropriate.
39-39: Improved function naming for clarity.Renaming
GetGroupModelstoGetGroupEnabledModelsmakes the function's purpose more explicit - it only returns enabled models.
64-97: Consistent use of boolean literals.Using the boolean literal
trueinstead of variables likecommonTrueValmakes the queries more explicit and easier to understand.constant/api_type.go (1)
1-34: Clean and comprehensive API type constants.The use of
iotafor API type enumeration is appropriate and the comprehensive list covers all major providers. TheAPITypeDummyconstant with its clear comment about being used only for counting is a good practice.common/gin.go (1)
48-78: Excellent type-safe context key helpers.The new helper functions provide a clean typed interface for Gin context access using
constant.ContextKey. This approach:
- Improves type safety by preventing raw string key usage
- Provides comprehensive coverage of common types (string, int, bool, time, etc.)
- Maintains compatibility with underlying Gin context methods
- Creates a consistent API for context key management
The implementation is clean and follows good Go patterns.
model/pricing.go (1)
49-60: Well-implemented thread-safe accessor.The function properly handles edge cases and uses appropriate locking for concurrent access. Returning empty slices instead of nil is a good practice.
controller/model.go (1)
108-173: Clean refactoring with improved context handling.The migration to use typed context keys and helper functions from the
commonpackage improves type safety and code consistency. The addition ofSupportedEndpointTypesenriches the model metadata appropriately.constant/channel.go (1)
56-109: Empty base URLs are intentional for these channels.The blank entries in
ChannelBaseURLscorrespond to channel types that don’t have a fixed default endpoint and instead require configuration at runtime:
- ChannelTypeUnknown (0)
- ChannelTypeCustom (8)
- ChannelTypePaLM (11)
- ChannelTypeXunfei (18)
- ChannelTypeSunoAPI (36)
- ChannelTypeVertexAi (41)
- ChannelTypeXinference (47)
No further changes needed.
✨ feat: refactor environment variable initialization
Summary by CodeRabbit
New Features
Bug Fixes
Documentation
Refactor
Chores