Skip to content

feat(model-mapping): support wildcard pattern and array mapping - #2406

Closed
longkeyy wants to merge 4850 commits into
QuantumNous:mainfrom
longkeyy:feat/wildcard-model-mapping
Closed

longkeyy wants to merge 4850 commits into
QuantumNous:mainfrom
longkeyy:feat/wildcard-model-mapping

Conversation

@longkeyy

@longkeyy longkeyy commented Dec 10, 2025 •

Copy link
Copy Markdown

Summary

This PR adds support for flexible model name mapping using wildcard patterns and array values, addressing the needs described in #1709 and #2170.

New Features

Wildcard Pattern Matching:

  • prefix*: matches model names with the given prefix (e.g., "Pro/*" matches "Pro/deepseek-ai/DeepSeek-R1")
  • *suffix: matches model names with the given suffix (e.g., "*DeepSeek-R1")
  • *contains*: matches model names containing the given substring (e.g., "*deepseek*")
  • *: matches any model name

Wildcard Replacement:

  • When target contains *, it will be replaced with the matched wildcard part
  • Example: "Pro/*": "*" will map "Pro/deepseek-ai/DeepSeek-R1" to "deepseek-ai/DeepSeek-R1"

Array Mapping (Many-to-One):

  • Support array values for reverse mapping multiple source models to one target
  • Example configuration:
{
  "DeepSeek-R1": ["Pro/deepseek-ai/DeepSeek-R1", "deepseek-ai/DeepSeek-R1"]
}
  • Both exact and wildcard patterns are supported within array items

Changes

  • Backend (relay/helper/model_mapped.go):

    • Added matchWildcard() function for pattern matching
    • Added findMappedModel() function supporting both exact and wildcard lookups
    • Added applyWildcardReplacement() for dynamic target model name generation
    • Modified ModelMappedHelper() to support array values and wildcard patterns
    • Added comprehensive unit tests (model_mapped_test.go)
  • Frontend (EditChannelModal.jsx):

    • Updated redirectModelList to handle array values
    • Added MODEL_MAPPING_ADVANCED_EXAMPLE with wildcard and array examples
    • Updated validation to skip wildcard patterns from missing model check
    • Updated UI placeholder text with usage instructions

Test Plan

  • Unit tests for matchWildcard() function covering all pattern types
  • Unit tests for applyWildcardReplacement() function
  • Unit tests for findMappedModel() function
  • All existing tests pass
  • Go build successful
  • Manual testing of model mapping in UI

Closes #1709, Closes #2170

Summary by CodeRabbit

  • New Features

    • Wildcard pattern matching and dynamic wildcard replacements in model mappings.
    • Multi-value (array) mappings supported, preserving priority/order for multi-source consolidation.
    • Improved mapping resolution with exact-match priority and cycle-safe behavior for more reliable routing.
  • Documentation / UI

    • Updated examples, templates, and explanatory text to show advanced wildcard and multi-value mapping.
  • Tests

    • Added comprehensive unit tests covering wildcard behavior, replacements, and mapping resolution.

✏️ Tip: You can customize this high-level summary in your review settings.

Calcium-Ion and others added 30 commits November 5, 2025 16:02
feat:  EditTokenModal 中针对用户创建的 token 默认无限额度
feat: add environment variable switch for critical rate limit
…80p-image

fix: trim suffix p for jimeng image model
…odisable

fix(channel): 当没有可用密钥时返回错误而不是第一个密钥
… new sections for partners, acknowledgments, and deployment instructions
- 更新中文README.md中的语言链接
- 完全重写英文README.en.md,包含所有详细功能说明
- 完全重写法文README.fr.md,确保内容一致性
- 完全重写日文README.ja.md,提供完整的项目说明

所有语言版本现在具有:
- 相同的结构和格式
- 一致的语言导航
- 完整的功能特性和部署指南
- 统一的环境变量配置说明
…ence

修复viduq2不支持参考生视频的问题
…annel

feat: replicate channel flux model
Calcium-Ion and others added 25 commits December 13, 2025 23:57
…itelist-cidr

feat(auth): enhance IP restriction handling with CIDR support
… meta when token count is disabled

Clamp request body size (including post-decompression) to avoid memory exhaustion caused by huge payloads/zip bombs, especially with large-context Claude requests. Add a configurable `MAX_REQUEST_BODY_MB` (default `32`) and document it.

- Enforce max request body size after gzip/br decompression via `http.MaxBytesReader`
- Add a secondary size guard in `common.GetRequestBody` and cache-safe handling
- Return **413 Request Entity Too Large** on oversized bodies in relay entry
- Avoid building large `TokenCountMeta.CombineText` when both token counting and sensitive check are disabled (use lightweight meta for pricing)
- Update READMEs (CN/EN/FR/JA) with `MAX_REQUEST_BODY_MB`
- Fix a handful of vet/formatting issues encountered during the change
- `go test ./...` passes
Tighten oversized request handling across relay paths and make error matching reliable.

- Align `MAX_REQUEST_BODY_MB` fallback to `32` in request body reader and decompression middleware
- Stop ignoring `GetRequestBody` errors in relay retry paths; return consistent **413** on oversized bodies (400 for other read errors)
- Add `Unwrap()` to `types.NewAPIError` so `errors.Is/As` can match wrapped underlying errors
- `go test ./...` passes
…-response-id

fix: 模型设置增加针对Vertex渠道过滤content[].part[].functionResponse.id的选项,默认启用
- Replace legacy `docs.newapi.pro` paths with the new `/{lang}/docs/...` structure across all README translations
- Point key sections (installation, env vars, API, support, features) to their new locations
- Ensure language-specific links use the correct locale prefix (zh/en/ja) and keep FR aligned with English routes
Keep new-site links (/{lang}/docs/...) where matching pages exist in the current docs repo
Revert links that have no equivalent in the new docs to the legacy paths on doc.newapi.pro:
Google Gemini Chat
Midjourney-Proxy image docs
Suno music docs
Apply the same rule consistently across all README translations (zh/en/ja/fr)
…te-doc-links-new-routing

🔗 docs(readme): update documentation links to new site routing
Add support for flexible model name mapping with the following features:

- Wildcard pattern matching:
  - `prefix*`: matches model names with the given prefix (e.g., "Pro/*")
  - `*suffix`: matches model names with the given suffix (e.g., "*DeepSeek-R1")
  - `*contains*`: matches model names containing the given substring
  - `*`: matches any model name

- Wildcard replacement in target:
  - When target contains `*`, it will be replaced with the matched wildcard part
  - Example: `"Pro/*": "*"` will map "Pro/deepseek-ai/DeepSeek-R1" to "deepseek-ai/DeepSeek-R1"

- Array mapping (many-to-one):
  - Support array values for reverse mapping multiple source models to one target
  - Example: `"DeepSeek-R1": ["Pro/deepseek-ai/DeepSeek-R1", "deepseek-ai/DeepSeek-R1"]`
  - Both exact and wildcard patterns supported in array items

- Updated frontend UI:
  - New advanced template with wildcard and array examples
  - Updated validation to skip wildcard patterns from missing model check
  - Updated placeholder text with usage instructions

Closes QuantumNous#1709 QuantumNous#2170
Address CodeRabbit review feedback:
- Use gjson to preserve JSON key order for deterministic matching
- Wildcard patterns now match in configuration order (first match wins)
- Add comprehensive docstrings for all exported functions
- Refactor code into smaller, well-documented functions
- Remove redundant logic in *contains* pattern handling

This gives users full control over matching priority by simply
ordering their patterns in the JSON configuration.
@longkeyy
longkeyy force-pushed the feat/wildcard-model-mapping branch from 75e84d0 to 045315c Compare December 23, 2025 16:01

@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 (1)
relay/helper/model_mapped.go (1)

211-224: Consider removing unused parameter modelMap from tryArrayMapping.

The modelMap parameter is passed to tryArrayMapping on line 219 but is never used inside the function. The function uses gjson.Parse(jsonStr) instead for order-preserving iteration.

🔎 Proposed fix
-	// Parse mapping for array handling (order doesn't matter for arrays)
-	modelMap := make(map[string]interface{})
-	if err := json.Unmarshal([]byte(modelMapping), &modelMap); err != nil {
-		return fmt.Errorf("unmarshal_model_mapping_failed")
-	}
-
 	// Phase 1: Check array (reverse) mappings first
 	// Format: "target": ["source1", "source2", "pattern*"]
-	if mapped := tryArrayMapping(modelMapping, modelMap, info); mapped {
+	if mapped := tryArrayMapping(modelMapping, info); mapped {
 		if request != nil {
 			request.SetModelName(info.UpstreamModelName)
 		}
 		return nil
 	}

And update the function signature:

-func tryArrayMapping(jsonStr string, modelMap map[string]interface{}, info *common.RelayInfo) bool {
+func tryArrayMapping(jsonStr string, info *common.RelayInfo) bool {
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 75e84d0 and 045315c.

📒 Files selected for processing (3)
  • relay/helper/model_mapped.go
  • relay/helper/model_mapped_test.go
  • web/src/components/table/channels/modals/EditChannelModal.jsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • relay/helper/model_mapped_test.go
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: AAEE86
Repo: QuantumNous/new-api PR: 1658
File: web/src/components/table/channels/modals/EditChannelModal.jsx:555-569
Timestamp: 2025-08-27T02:15:25.448Z
Learning: In EditChannelModal.jsx, the applyModelMapping function transforms the models list by replacing original model names (mapping values) with display names (mapping keys). The database stores this transformed list containing mapped keys. On channel load, data.models contains these mapped display names, making the initialization filter if (data.models.includes(key)) correct.
📚 Learning: 2025-08-27T02:15:25.448Z
Learnt from: AAEE86
Repo: QuantumNous/new-api PR: 1658
File: web/src/components/table/channels/modals/EditChannelModal.jsx:555-569
Timestamp: 2025-08-27T02:15:25.448Z
Learning: In EditChannelModal.jsx, the applyModelMapping function transforms the models list by replacing original model names (mapping values) with display names (mapping keys). The database stores this transformed list containing mapped keys. On channel load, data.models contains these mapped display names, making the initialization filter if (data.models.includes(key)) correct.

Applied to files:

  • web/src/components/table/channels/modals/EditChannelModal.jsx
📚 Learning: 2025-08-27T02:15:25.448Z
Learnt from: AAEE86
Repo: QuantumNous/new-api PR: 1658
File: web/src/components/table/channels/modals/EditChannelModal.jsx:555-569
Timestamp: 2025-08-27T02:15:25.448Z
Learning: In EditChannelModal.jsx, the database stores mapped keys (display names) in the models field after applying model mapping transformations. When loading a channel, data.models contains the mapped keys, not the original model names. The filtering logic if (data.models.includes(key)) in the initialization is correct.

Applied to files:

  • web/src/components/table/channels/modals/EditChannelModal.jsx
🧬 Code graph analysis (1)
relay/helper/model_mapped.go (3)
relay/common/relay_info.go (1)
  • RelayInfo (82-130)
dto/request_common.go (1)
  • Request (8-12)
common/json.go (1)
  • Unmarshal (9-11)
🔇 Additional comments (9)
web/src/components/table/channels/modals/EditChannelModal.jsx (4)

81-86: LGTM!

The advanced example clearly demonstrates all new mapping features: direct mapping, prefix wildcard with replacement, and array-based reverse mapping.


214-229: LGTM!

The updated logic correctly handles both string and array values, properly filters out wildcard-only entries, and maintains backward compatibility.


1146-1149: LGTM!

Correctly excludes wildcard patterns from the missing-models validation since they match dynamically rather than representing specific models.


2580-2594: LGTM!

UI updates clearly communicate the new wildcard and array mapping capabilities to users.

relay/helper/model_mapped.go (5)

15-60: LGTM!

Well-structured wildcard matching with comprehensive pattern support and clear documentation.


62-129: LGTM!

The implementation now uses gjson.ForEach for order-preserving iteration, addressing the previous concern about non-deterministic behavior when multiple patterns match. Users can control priority through JSON key order.


131-171: LGTM!

Clean implementation of wildcard replacement with well-documented behavior for edge cases.


251-286: LGTM!

The array mapping logic correctly supports both exact and wildcard matches within arrays, with order-preserving iteration for predictable priority.


288-334: LGTM!

Robust chain resolution with proper cycle detection. The handling of self-mapping edge cases (at start vs. after chain) is well thought out.

@DreamfulWong

Copy link
Copy Markdown

合并了吗?好像主分支没有更新,容器镜像也没有,模型映射用不了数组

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet