Skip to content

✨ feat: refactor environment variable initialization - #1326

Merged
Calcium-Ion merged 1 commit into
alphafrom
refactor_constant
Jul 3, 2025
Merged

✨ feat: refactor environment variable initialization#1326
Calcium-Ion merged 1 commit into
alphafrom
refactor_constant

Conversation

@Calcium-Ion

@Calcium-Ion Calcium-Ion commented Jul 3, 2025

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • New Features

    • Models now display their supported endpoint types, enhancing transparency for users.
    • Added new helper functions for consistent and type-safe context data handling.
    • Improved tracking and display of model capabilities and supported channels.
  • Bug Fixes

    • Fixed inconsistencies in channel type and API type references for improved reliability.
  • Documentation

    • Added detailed documentation for constants and package usage conventions.
  • Refactor

    • Streamlined how models and channels are managed and referenced.
    • Simplified context key usage and improved environment initialization.
  • Chores

    • Introduced a generic Set data structure for improved internal data handling.

@coderabbitai

coderabbitai Bot commented Jul 3, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

This change refactors the handling of channel and API type constants by moving their definitions from the common package to a new constant package. It introduces new helper functions for context key management, updates model and pricing structures to include supported endpoint types, and adds generic set utilities. The codebase is updated to use the new constant locations and helper functions throughout.

Changes

Files / Groups Change Summary
common/api_type.go, constant/api_type.go, relay/constant/api_type.go API type constants and mapping function moved from relay/constant to constant, with new mapping logic in common/api_type.go.
common/constants.go, constant/channel.go Channel type constants and base URLs moved from common to constant package.
common/endpoint_type.go, constant/endpoint_type.go Endpoint type constants and mapping logic introduced in constant, with channel-to-endpoint mapping in common.
common/gin.go Added typed Gin context key helper functions for setting and getting values.
common/init.go, constant/env.go Environment initialization refactored; moved from constant/env.go to common/init.go, with improved modularity.
common/model.go Added OpenAI response-only models list and membership check function.
common/redis.go, constant/cache_key.go Redis cache seconds function moved from constant to common.
controller/*.go, relay/channel/openai/adaptor.go, relay/common/relay_info.go, relay/common/relay_utils.go, relay/common_handler/rerank.go, service/*.go, middleware/*.go, model/token_cache.go, model/user_cache.go Updated to use constants and helpers from the new constant package and context key helpers from common.
controller/model.go, dto/pricing.go, model/pricing.go Model and pricing structs updated: removed permission fields, added supported endpoint types, improved concurrency in pricing logic.
model/ability.go Added struct for ability with channel, new query for enabled abilities with channel type, renamed group model function for clarity.
types/set.go Introduced a generic Set type with standard set operations.
constant/context_key.go Introduced typed context keys and expanded key set for tokens, channels, and users.
constant/README.md Added documentation for the constant package, its files, and usage conventions.
main.go Consolidated environment initialization; added pricing initialization.

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
Loading

Possibly related PRs

Poem

In fields of code where constants roam,
We gathered them and brought them home.
With sets and helpers, keys anew,
The context clearer, purpose true.
Models now know endpoints well—
The rabbit hops, and all is swell!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

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.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need 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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 constant and commonconstant aliases 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 GetTaskAdaptor function:

-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.StringsContains which 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

📥 Commits

Reviewing files that changed from the base of the PR and between 34aca14 and 7e298f8.

📒 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/constant to constant is 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.ChannelTypeGemini to constant.ChannelTypeGemini aligns 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.ChannelTypeDeepSeek to constant.ChannelTypeDeepSeek is 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 common package to the constant package. The logic remains unchanged and the constant is properly defined in constant/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 the constant package to the common package 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 constant package. The logic remains unchanged and the constant is properly defined in constant/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 GetFullRequestURL function logic remains unchanged and both constants are properly defined in constant/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 common to constant package maintains the exact same conditional logic for image token calculation. All three channel type constants are properly defined in constant/channel.go and 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 common package to the constant package 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() to common.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.ChannelBaseURLs to constant.ChannelBaseURLs is consistent with the broader refactoring effort to move channel-related constants to the constant package.

model/token_cache.go (1)

13-13: LGTM! Correct placement of configuration function in common package.

The change from constant.RedisKeyCacheSeconds() to common.RedisKeyCacheSeconds() correctly moves this environment/configuration-related function to the common package where it belongs, while keeping type constants in the constant package.

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 with common.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 GetGroupModels to GetGroupEnabledModels correctly 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() after model.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 constant package aligns with the refactoring to centralize constants.


17-17: LGTM! Import alias prevents naming conflicts.

Using relayconstant as an alias for the relay constant package prevents naming conflicts with the global constant package.


72-72: LGTM! Consistent use of updated import alias.

The function calls are correctly updated to use the relayconstant alias, maintaining consistency throughout the file.

Also applies to: 135-135


298-298: LGTM! Channel type constant moved to constant package.

The change from common.ChannelTypeAnthropic to constant.ChannelTypeAnthropic aligns with the refactoring to centralize channel type constants in the constant package.

constant/endpoint_type.go (1)

1-11: LGTM! Well-designed type definition.

The new EndpointType as 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 to common.SetContextKey() with typed constant.ContextKey constants improves type safety and consistency across the codebase.


73-73: LGTM! Function relocated to appropriate package.

The change from constant.RedisKeyCacheSeconds() to common.RedisKeyCacheSeconds() aligns with the package reorganization, moving cache-related utilities to the common package.

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 common package to the appropriate new locations (constant for channel types and relayconstant for 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 constant package 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 SupportedEndpointTypes provides a more flexible and dynamic approach to representing model capabilities. This change aligns well with the endpoint type system introduced in the constant package.

common/model.go (2)

5-12: LGTM! Clear model categorization with good documentation.

The OpenAIResponseOnlyModels list 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 if modelName is contained within each predefined model m. 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 constant2 alias and direct import of constant package 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 constant package 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.ContextKey constants

This 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 constant package 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.ChannelBaseURLs to constant.ChannelBaseURLs is 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 constant package 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 ChannelTypeVertexAi have 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 ChannelBaseURLs has 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 initConstantEnv function.


28-28: LGTM: Function rename improves clarity.

Renaming from InitCommonEnv to InitEnv better reflects the function's broader scope of initializing environment variables across packages.


100-101: LGTM: Modular initialization approach.

Calling initConstantEnv() at the end of InitEnv() provides a clean separation of concerns for initializing different package variables.


103-120: LGTM: Comprehensive constant environment initialization.

The initConstantEnv function 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 constant package 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.ChannelTypeMokaAI maintains consistency with other channel type constant changes.


105-105: LGTM: Correct usage of relocated mapping function.

Using common.ChannelType2APIType is 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 APITypeOpenAI as the default with false success 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 fallthrough for 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 streamSupportedChannels map to use constants from the constant package 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 typed constant.ContextKey approach.


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 the common package.


269-275: Consistent constant package usage.

The updates to use constant.ChannelBaseURLs, constant.ChannelTypeAzure, and constant.ChannelTypeVertexAi are consistent with the constant centralization effort.

model/ability.go (4)

24-27: Good design: Extended struct for ability-channel relationship.

The AbilityWithChannel struct that embeds Ability and adds ChannelType is a clean way to represent the joined data without modifying the base Ability struct.


29-37: Well-implemented JOIN query.

The GetAllEnableAbilityWithChannels function 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 GetGroupModels to GetGroupEnabledModels makes the function's purpose more explicit - it only returns enabled models.


64-97: Consistent use of boolean literals.

Using the boolean literal true instead of variables like commonTrueVal makes the queries more explicit and easier to understand.

constant/api_type.go (1)

1-34: Clean and comprehensive API type constants.

The use of iota for API type enumeration is appropriate and the comprehensive list covers all major providers. The APITypeDummy constant 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 common package improves type safety and code consistency. The addition of SupportedEndpointTypes enriches the model metadata appropriately.

constant/channel.go (1)

56-109: Empty base URLs are intentional for these channels.

The blank entries in ChannelBaseURLs correspond 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.

@Calcium-Ion
Calcium-Ion merged commit 123862d into alpha Jul 3, 2025
@Calcium-Ion
Calcium-Ion deleted the refactor_constant branch July 12, 2025 04:11
@coderabbitai coderabbitai Bot mentioned this pull request Jan 13, 2026
@coderabbitai coderabbitai Bot mentioned this pull request Apr 18, 2026
9 tasks
x22x22 pushed a commit to x22x22/new-api that referenced this pull request Apr 24, 2026
✨ feat: refactor environment variable initialization
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant