Repository navigation
feat: 允许设置不进行thinking尾后缀去除的黑名单 - #2189
Conversation
WalkthroughThis PR introduces a configurable blacklist to control when the "-thinking" suffix should be preserved on specific models. It adds a new Changes
Sequence DiagramsequenceDiagram
participant Client
participant Adapter as Relay Adapter
participant Blacklist as ShouldPreserveThinkingSuffix<br/>(originModelName)
participant Upstream as Upstream API
Client->>Adapter: Request with model (e.g., "model-thinking")
Adapter->>Blacklist: Check if model in blacklist
alt Model NOT in blacklist
Blacklist-->>Adapter: false (strip suffix)
Adapter->>Adapter: Remove "-thinking" suffix
Adapter->>Upstream: Send request with clean model name
else Model IS in blacklist
Blacklist-->>Adapter: true (preserve suffix)
Adapter->>Upstream: Send request with original model name
end
Upstream-->>Adapter: Response
Adapter-->>Client: Response
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes
Possibly related PRs
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (2)
relay/channel/vertex/adaptor.go (1)
171-182: Good guard; prevents unintended suffix normalization for blacklisted models.The combined check with ThinkingAdapterEnabled and ShouldPreserveThinkingSuffix(info.OriginModelName) looks correct.
- Please confirm region resolution via GetModelRegion(info.ApiVersion, info.OriginModelName) is still correct when UpstreamModelName is normalized (no suffix). If region mapping depends on suffixless names, this is fine; otherwise, consider aligning inputs.
- Consider extracting a shared helper for “thinking-suffix normalization” to keep logic identical across channels.
web/src/pages/Setting/Model/SettingGlobalModel.jsx (1)
151-181: Label/UX nits (optional).
- Consider rewording the label to emphasize preservation, e.g., “保留 -thinking/-nothinking 后缀的模型” to avoid ambiguity with “禁用思考处理”.
- Placeholder could reuse a dedicated i18n like “请输入JSON数组,如 ["model-a","model-b"]” for consistency across locales.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (14)
relay/channel/claude/relay-claude.go(1 hunks)relay/channel/gemini/adaptor.go(1 hunks)relay/channel/openai/adaptor.go(2 hunks)relay/channel/vertex/adaptor.go(1 hunks)relay/channel/volcengine/adaptor.go(2 hunks)relay/claude_handler.go(1 hunks)setting/model_setting/global.go(2 hunks)web/src/components/settings/ModelSetting.jsx(2 hunks)web/src/i18n/locales/en.json(1 hunks)web/src/i18n/locales/fr.json(1 hunks)web/src/i18n/locales/ja.json(1 hunks)web/src/i18n/locales/ru.json(1 hunks)web/src/i18n/locales/zh.json(1 hunks)web/src/pages/Setting/Model/SettingGlobalModel.jsx(3 hunks)
🧰 Additional context used
🧠 Learnings (5)
📓 Common learnings
Learnt from: neotf
Repo: QuantumNous/new-api PR: 1511
File: setting/ratio_setting/model_ratio.go:118-123
Timestamp: 2025-08-05T17:14:17.246Z
Learning: Claude models handle "-thinking" variants differently from Gemini models. For Claude models, only the base model (without "-thinking") gets an entry in defaultModelRatio map. The "-thinking" variants rely on the Claude relay handler stripping the suffix using strings.TrimSuffix(textRequest.Model, "-thinking") before looking up the ratio, so they automatically use the base model's ratio.
📚 Learning: 2025-06-21T03:37:41.726Z
Learnt from: 9Ninety
Repo: QuantumNous/new-api PR: 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.
Applied to files:
relay/channel/gemini/adaptor.gorelay/channel/vertex/adaptor.gorelay/claude_handler.go
📚 Learning: 2025-08-05T17:14:17.246Z
Learnt from: neotf
Repo: QuantumNous/new-api PR: 1511
File: setting/ratio_setting/model_ratio.go:118-123
Timestamp: 2025-08-05T17:14:17.246Z
Learning: Claude models handle "-thinking" variants differently from Gemini models. For Claude models, only the base model (without "-thinking") gets an entry in defaultModelRatio map. The "-thinking" variants rely on the Claude relay handler stripping the suffix using strings.TrimSuffix(textRequest.Model, "-thinking") before looking up the ratio, so they automatically use the base model's ratio.
Applied to files:
relay/channel/gemini/adaptor.gorelay/claude_handler.gorelay/channel/openai/adaptor.gorelay/channel/claude/relay-claude.gorelay/channel/volcengine/adaptor.go
📚 Learning: 2025-08-08T17:12:43.157Z
Learnt from: RedwindA
Repo: QuantumNous/new-api PR: 1537
File: relay/gemini_handler.go:330-342
Timestamp: 2025-08-08T17:12:43.157Z
Learning: In the new-api repository, the `GeminiEmbeddingHandler` function in `relay/gemini_handler.go` is designed specifically for native Gemini embedding requests and therefore does not require the `ConvertGeminiRequest` step that is used in the chat handler. The embedding requests are already in the native Gemini format and don't need conversion.
Applied to files:
relay/channel/gemini/adaptor.gorelay/channel/vertex/adaptor.go
📚 Learning: 2025-08-21T06:31:11.073Z
Learnt from: jiajunly
Repo: QuantumNous/new-api PR: 1629
File: relay/channel/openai/relay-openai.go:170-174
Timestamp: 2025-08-21T06:31:11.073Z
Learning: In relay/channel/openai/relay-openai.go, the streaming logic for the AddThinkFirst feature is designed so that only the first chunk of a stream gets the "<think>\n" prefix. The final flush in the streaming handler intentionally uses addThink=false because the last chunk should never receive the prefix, even in single-chunk streams where the prefix would have been applied during normal processing.
Applied to files:
relay/claude_handler.gorelay/channel/openai/adaptor.gorelay/channel/claude/relay-claude.gorelay/channel/volcengine/adaptor.go
🧬 Code graph analysis (7)
relay/channel/gemini/adaptor.go (2)
setting/model_setting/gemini.go (1)
GetGeminiSettings(43-45)setting/model_setting/global.go (1)
ShouldPreserveThinkingSuffix(36-48)
relay/channel/vertex/adaptor.go (2)
setting/model_setting/gemini.go (1)
GetGeminiSettings(43-45)setting/model_setting/global.go (1)
ShouldPreserveThinkingSuffix(36-48)
relay/claude_handler.go (1)
setting/model_setting/global.go (1)
ShouldPreserveThinkingSuffix(36-48)
relay/channel/openai/adaptor.go (1)
setting/model_setting/global.go (1)
ShouldPreserveThinkingSuffix(36-48)
relay/channel/claude/relay-claude.go (1)
setting/model_setting/global.go (1)
ShouldPreserveThinkingSuffix(36-48)
relay/channel/volcengine/adaptor.go (1)
setting/model_setting/global.go (1)
ShouldPreserveThinkingSuffix(36-48)
web/src/pages/Setting/Model/SettingGlobalModel.jsx (2)
web/src/components/settings/ModelSetting.jsx (1)
inputs(31-45)web/src/helpers/utils.jsx (1)
compareObjects(298-315)
🔇 Additional comments (15)
setting/model_setting/global.go (2)
10-21: LGTM! Clean implementation of the blacklist configuration.The new
ThinkingModelBlacklistfield is well-integrated into the existing global settings structure, with sensible defaults for Kimi models that handle thinking processing internally.
35-48: Well-implemented with good defensive programming.The function correctly handles edge cases:
- Trims whitespace from both the input and blacklist entries for robust matching
- Returns
falsefor empty model names- Uses case-sensitive comparison, which is appropriate for model identifiers
web/src/i18n/locales/ja.json (1)
564-566: LGTM! Localization entries added for the thinking model blacklist feature.The Japanese translations properly support the new UI functionality.
web/src/i18n/locales/zh.json (1)
561-563: LGTM! Chinese localization entries added.The translation keys properly describe the thinking model blacklist configuration.
relay/channel/gemini/adaptor.go (1)
130-141: LGTM! Correctly gates the thinking suffix handling.The additional check ensures that models in the blacklist bypass the thinking suffix processing, using
info.OriginModelNameto check against the original model name before any mapping. This preserves the intended behavior for models like Kimi that handle thinking internally.relay/channel/claude/relay-claude.go (1)
192-194: LGTM! Conditional suffix trimming correctly implemented.The check prevents trimming the "-thinking" suffix for blacklisted models. Note that this uses
textRequest.Model(the model from the request parameter) while other adapters useinfo.OriginModelName. Both should contain the same original model name at this point in the conversion flow, so the behavior is consistent.relay/channel/volcengine/adaptor.go (2)
19-19: LGTM! Required import added for the new functionality.
295-301: LGTM! Thinking suffix handling correctly gated for Volcengine/Deepseek models.The additional check ensures that only Deepseek models with the "-thinking" suffix that are NOT in the blacklist undergo the thinking adapter processing. This preserves the suffix for any blacklisted models while maintaining the existing behavior for others.
relay/claude_handler.go (1)
70-73: LGTM! Conditional suffix trimming correctly applied.The check ensures the "-thinking" suffix is preserved for blacklisted models while allowing normal processing for others. The
info.UpstreamModelNameis correctly set from the conditionally-trimmed model name, maintaining proper state for downstream processing.web/src/components/settings/ModelSetting.jsx (1)
40-40: Default value LGTM.Initializing 'global.thinking_model_blacklist' to '[]' is sensible.
relay/channel/openai/adaptor.go (2)
30-30: Import addition LGTM.
228-247: Conditional trim aligns with the new preserve list.Only stripping “-thinking” when ShouldPreserveThinkingSuffix(origin) is false is correct. Reasoning payload patching remains intact.
- Does OpenRouter ever send/expect “-nothinking”? If yes, mirror the guard to also strip “-nothinking” (or explicitly ignore). If no, current scope is fine.
web/src/pages/Setting/Model/SettingGlobalModel.jsx (1)
32-36: LGTM: sensible defaults and robust initialization.
- Example JSON and defaults are clear.
- State mirrors defaults.
- useEffect safely normalizes blacklist with try/catch and updates form via ref guard.
Also applies to: 38-44, 49-52, 98-114, 119-121
web/src/i18n/locales/en.json (1)
564-566: The review comment is incorrect; no changes are required.The typo "-nothotinking" does not exist in the file—it already correctly shows "-nothinking". Additionally, the i18n key "请输入JSON数组..." is actively used in the codebase for Vertex AI JSON array channel key handling (see ChannelKeyDisplay.jsx and controller/channel.go). The key is not stale.
Likely an incorrect or invalid review comment.
web/src/i18n/locales/ru.json (1)
570-572: Translation entries are appropriate and consistent.The three new translation entries for the thinking model blacklist feature are well-integrated into the Russian locale file:
- Line 570: Appropriately uses the English technical term "thinking" alongside Russian ("обработки thinking"), which is consistent with how technical terms are handled throughout the file.
- Line 571: Accurately translates the feature description and properly conveys the meaning about suffix handling.
- Line 572: Clear and straightforward instruction with correct JSON array formatting examples.
The entries are correctly placed in alphabetical order and follow the existing formatting conventions.
| item.key === 'gemini.supported_imagine_models' || | ||
| item.key === 'global.thinking_model_blacklist' | ||
| ) { |
There was a problem hiding this comment.
Harden JSON formatting to avoid breaking refresh on bad data.
JSON.parse may throw; today on error onRefresh() will show “刷新失败” and leave page stale.
Apply this minimal guard:
- item.key === 'gemini.supported_imagine_models' ||
- item.key === 'global.thinking_model_blacklist'
+ item.key === 'gemini.supported_imagine_models' ||
+ item.key === 'global.thinking_model_blacklist'
) {
- if (item.value !== '') {
- item.value = JSON.stringify(JSON.parse(item.value), null, 2);
- }
+ if (item.value !== '') {
+ try {
+ item.value = JSON.stringify(JSON.parse(item.value), null, 2);
+ } catch (_) {
+ // keep raw; UI will show verify error in detail form
+ }
+ }
}
🤖 Prompt for AI Agents
In web/src/components/settings/ModelSetting.jsx around lines 60-62, the code
assumes JSON.parse on stored item keys always succeeds; a thrown error breaks
onRefresh() and leaves the page stale. Wrap JSON.parse in a try/catch (or use a
safeParse helper) when reading those keys, on parse error log/report the error,
fall back to a sensible default (e.g., [] or {} depending on expected shape),
and continue execution so the refresh completes; ensure any downstream code
handles the default shape to avoid further exceptions.
| "禁用思考处理的模型列表": "Liste noire des modèles pour le traitement thinking", | ||
| "列出的模型将不会自动添加或移除-thinking/-nothinking 后缀": "Les modèles listés ici n'ajouteront ni ne retireront automatiquement le suffixe -thinking/-nothinking.", | ||
| "请输入JSON数组,如 [\"model-a\",\"model-b\"]": "Saisissez un tableau JSON, par ex. [\"model-a\",\"model-b\"]", |
There was a problem hiding this comment.
Polish FR phrasing and fix wording.
Improve translation clarity.
Apply:
- "禁用思考处理的模型列表": "Liste noire des modèles pour le traitement thinking",
- "列出的模型将不会自动添加或移除-thinking/-nothinking 后缀": "Les modèles listés ici n'ajouteront ni ne retireront automatiquement le suffixe -thinking/-nothinking.",
- "请输入JSON数组,如 [\"model-a\",\"model-b\"]": "Saisissez un JSON array, par ex. [\"model-a\",\"model-b\"]"
+ "禁用思考处理的模型列表": "Modèles excluant le traitement « thinking »",
+ "列出的模型将不会自动添加或移除-thinking/-nothinking 后缀": "Les modèles listés n’ajoutent ni ne retirent automatiquement le suffixe -thinking/-nothinking.",
+ "请输入JSON数组,如 [\"model-a\",\"model-b\"]": "Saisissez un tableau JSON, p. ex. [\"model-a\",\"model-b\"]"Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In web/src/i18n/locales/fr.json around lines 567-569, the French strings are
awkwardly phrased; replace them with clearer translations: for key "禁用思考处理的模型列表"
use "Liste noire des modèles pour le traitement « thinking »", for
"列出的模型将不会自动添加或移除-thinking/-nothinking 后缀" use "Les modèles listés ici n'auront
pas automatiquement le suffixe « -thinking » ou « -nothinking » ajouté ou
retiré.", and for "请输入JSON数组,如 [\"model-a\",\"model-b\"]" use "Veuillez saisir
un tableau JSON, par ex. [\"model-a\",\"model-b\"]". Ensure proper punctuation
and smart quotes as shown.
| const normalizeValueBeforeSave = (key, value) => { | ||
| if (key === 'global.thinking_model_blacklist') { | ||
| const text = typeof value === 'string' ? value.trim() : ''; | ||
| return text === '' ? '[]' : value; | ||
| } | ||
| return value; | ||
| }; |
There was a problem hiding this comment.
Block invalid JSON before save; optional: minify payload.
Add a fast guard so bad JSON can’t be persisted, and (optionally) store minified JSON to reduce diffs.
Apply this:
function onSubmit() {
- const updateArray = compareObjects(inputs, inputsRow);
+ // guard: prevent invalid JSON save
+ const raw = inputs['global.thinking_model_blacklist'];
+ if (typeof raw === 'string' && raw.trim() !== '' && !verifyJSON(raw)) {
+ return showError(t('不是合法的 JSON 字符串'));
+ }
+ const updateArray = compareObjects(inputs, inputsRow);
@@
- const normalizedValue = normalizeValueBeforeSave(
- item.key,
- inputs[item.key],
- );
- let value = String(normalizedValue);
+ const normalizedValue = normalizeValueBeforeSave(item.key, inputs[item.key]);
+ // optional: store minified JSON for the blacklist
+ let value = String(normalizedValue);
+ if (item.key === 'global.thinking_model_blacklist' && verifyJSON(value)) {
+ try { value = JSON.stringify(JSON.parse(value)); } catch (_) {}
+ }Also applies to: 65-70
🤖 Prompt for AI Agents
In web/src/pages/Setting/Model/SettingGlobalModel.jsx around lines 53-59 (and
similarly 65-70) the current normalizeValueBeforeSave blindly allows non-JSON or
formatted JSON to be saved; update the function to validate the JSON for the
'global.thinking_model_blacklist' key by trimming and if empty returning '[]',
otherwise attempt to JSON.parse the trimmed string and on success return the
minified form JSON.stringify(parsed) to reduce diffs; if JSON.parse throws,
prevent saving by returning the previous valid value (or null/throw an error
handled upstream) and log or surface a validation error so invalid JSON is not
persisted.
* main: (77 commits) refactor(adaptor): Comment out enable_thinking logic for clarity and future adjustments fix GetChannelKey AdminAuth -> RootAuth fix GetChannelKey AdminAuth -> RootAuth feat: vidu reference2video only viduq2 feat: vidu specify reference2video via metadata action 同步多语言README文档 chore: Update README.md for improved structure and clarity, including new sections for partners, acknowledgments, and deployment instructions feat: replicate channel flux model feat: ShouldPreserveThinkingSuffix (#2189) fix(channel): 当没有可用密钥时返回错误而不是第一个密钥 fix: update tag normalization regex feat: restrict automatic channel testing to master node only feat: EditTagModal header && param (#2159) add custom tool (#2157) fix playground (#2153) feat: add TASK_PRICE_PATCH environment variable for per-task billing configuration feat: EditTokenModal 中针对用户创建的 token 默认无限额度 feat: add environment variable switch for critical rate limit feat: enhance Ali video request processing with resolution mapping and size validation fix: logger ...
fix #2183
Summary by CodeRabbit
Release Notes