Skip to content

feat(relay): preserve original model name in mapped responses - #4451

Closed
zhusichuang wants to merge 1 commit into
QuantumNous:mainfrom
trainkr:feat-response-model-original
Closed

zhusichuang wants to merge 1 commit into
QuantumNous:mainfrom
trainkr:feat-response-model-original

Conversation

@zhusichuang

@zhusichuang zhusichuang commented Apr 25, 2026 •

Copy link
Copy Markdown

⚠️ 提交说明 / PR Notice

Important

  • 请提供人工撰写的简洁摘要,避免直接粘贴未经整理的 AI 输出。

📝 变更描述 / Description

新增全局设置 global.response_model_original_enabled,用于控制模型映射生效时响应中的 model 字段是否返回客户端请求的原始模型名。

该设置开启后,OpenAI / Claude / Gemini 相关兼容响应会在返回前将客户端可见的 model 字段改回请求模型名,避免暴露映射后的上游模型名。计费、token 统计和上游请求仍继续使用真实上游模型名,不影响路由和结算逻辑。

🚀 变更类型 / Type of change

  • 🐛 Bug 修复 (Bug fix) - 请关联对应 Issue,避免将设计取舍、理解偏差或预期不一致直接归类为 bug
  • ✨ 新功能 (New feature) - 重大特性建议先通过 Issue 沟通
  • ⚡ 性能优化 / 重构 (Refactor)
  • 📝 文档更新 (Documentation)

🔗 关联任务 / Related Issue

  • Closes # (如有)

✅ 提交前检查项 / Checklist

  • 人工确认: 我已亲自整理并撰写此描述,没有直接粘贴未经处理的 AI 输出。
  • 非重复提交: 我已搜索现有的 Issues 与 PRs,确认不是重复提交。
  • Bug fix 说明: 若此 PR 标记为 Bug fix,我已提交或关联对应 Issue,且不会将设计取舍、预期不一致或理解偏差直接归类为 bug。
  • 变更理解: 我已理解这些更改的工作原理及可能影响。
  • 范围聚焦: 本 PR 未包含任何与当前任务无关的代码改动。
  • 本地验证: 已在本地运行并通过测试或手动验证,维护者可以据此复核结果。
  • 安全合规: 代码中无敏感凭据,且符合项目代码规范。

📸 运行证明 / Proof of Work

  • 已执行 git diff --check,无 whitespace/error 输出。
  • 当前环境缺少 go、gofmt、bun,未能运行 Go 测试和前端构建。

Summary by CodeRabbit

  • New Features
    • Added response model name rewriting for different AI providers (Claude, Gemini, OpenAI) based on client configuration.
    • New global setting response_model_original_enabled to control whether original model names are used in responses.
    • Updated settings UI to expose the new response model configuration option.

@coderabbitai

coderabbitai Bot commented Apr 25, 2026 •

Copy link
Copy Markdown
Contributor

Walkthrough

This PR introduces client-specific model name rewriting across relay channels. A new global setting response_model_original_enabled controls whether response model names are rewritten. A new function ResponseModelNameForClient handles the rewrite logic, systematically applied throughout Claude, Gemini, and OpenAI handlers in streaming and non-streaming paths.

Changes

Cohort / File(s) Summary
Model Rewriting Infrastructure
relay/common/response_model.go
Introduces exported ResponseModelNameForClient() function that validates relay info, checks global setting, and returns rewrite decision with original model name.
Global Configuration
setting/model_setting/global.go, web/src/components/settings/ModelSetting.jsx, web/src/pages/Setting/Model/SettingGlobalModel.jsx
Adds new boolean global setting response_model_original_enabled (default true) with UI toggle in settings component.
Claude Relay Handler
relay/channel/claude/relay-claude.go
Rewrites response model names in Claude-to-OpenAI and passthrough paths; patches streaming chunk JSON and non-stream response payloads to update both model and message.model fields when rewriting is enabled.
Claude Handler Tests
relay/channel/claude/relay_claude_test.go
Updates FormatClaudeResponseInfo call signatures to match modified function parameter order.
Gemini Relay Handlers
relay/channel/gemini/relay-gemini.go
Adds client-specific model name rewriting in streaming, non-streaming, and embedding response paths; computes responseModel via rewrite function and applies it to all generated messages.
OpenAI Relay Handlers
relay/channel/openai/chat_via_responses.go, relay/channel/openai/helper.go, relay/channel/openai/relay-openai.go
Conditionally rewrites model names in chat completions streaming/non-streaming paths and Claude format conversion; updates ChatCompletionsStreamResponse.Model and patches raw JSON bodies when rewriting is needed.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • seefs001
  • Calcium-Ion

Poem

🐰 A rabbit hops through relay streams,
Rewriting models in your dreams,
Each channel now knows what to show—
The client's name will gently flow! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat(relay): preserve original model name in mapped responses' directly describes the main feature introduced across the changeset—the preservation of original model names in client responses when model mapping is active.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@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: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
relay/channel/openai/helper.go (1)

55-79: ⚠️ Potential issue | 🟡 Minor

Apply model rewrite to handleGeminiFormat and Gemini branch of HandleFinalResponse for consistency with Claude paths.

handleClaudeFormat (lines 41–43) applies relaycommon.ResponseModelNameForClient(info) to rewrite streamResponse.Model after unmarshalling, but handleGeminiFormat (lines 55–79) and the Gemini branch of HandleFinalResponse (lines 234–262) do not. This creates an inconsistency where Claude-format clients receive the client-requested model name while Gemini-format clients receive the upstream provider's model name.

Add the same rewrite logic to both functions:

♻️ Proposed fix
 func handleGeminiFormat(c *gin.Context, data string, info *relaycommon.RelayInfo) error {
 	var streamResponse dto.ChatCompletionsStreamResponse
 	if err := common.Unmarshal(common.StringToByteSlice(data), &streamResponse); err != nil {
 		logger.LogError(c, "failed to unmarshal stream response: "+err.Error())
 		return err
 	}
+	if rewriteModel, responseModel := relaycommon.ResponseModelNameForClient(info); rewriteModel {
+		streamResponse.Model = responseModel
+	}
 
 	geminiResponse := service.StreamResponseOpenAI2Gemini(&streamResponse, info)

In HandleFinalResponse Gemini branch:

 case types.RelayFormatGemini:
 	var streamResponse dto.ChatCompletionsStreamResponse
 	if err := common.Unmarshal(common.StringToByteSlice(lastStreamData), &streamResponse); err != nil {
 		common.SysLog("error unmarshalling stream response: " + err.Error())
 		return
 	}
+	if rewriteModel, responseModel := relaycommon.ResponseModelNameForClient(info); rewriteModel {
+		streamResponse.Model = responseModel
+	}
 
 	geminiResponse := service.StreamResponseOpenAI2Gemini(&streamResponse, info)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@relay/channel/openai/helper.go` around lines 55 - 79, After unmarshalling in
handleGeminiFormat and in the Gemini branch of HandleFinalResponse, set the
stream response's Model to the client-facing name by assigning
streamResponse.Model = relaycommon.ResponseModelNameForClient(info) (or
equivalent on the final response struct) before converting to geminiResponse and
before marshalling/sending; ensure you perform this rewrite immediately after
common.Unmarshal and before calling service.StreamResponseOpenAI2Gemini (in
handleGeminiFormat) and before marshalling/sending in the Gemini final-response
path so Gemini clients see the client-requested model name just like Claude
paths.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@setting/model_setting/global.go`:
- Around line 37-45: The default for ResponseModelOriginalEnabled currently set
to true in defaultOpenaiSettings causes a backward-incompatible change; change
ResponseModelOriginalEnabled to false in the GlobalSettings default
(defaultOpenaiSettings) so the new behavior is opt-in, and update the frontend
default settings in the corresponding ModelSetting.jsx and
SettingGlobalModel.jsx components to the same false default to keep UI and
backend consistent; if keeping true was intentional, document it clearly in the
PR description/release notes instead.

---

Outside diff comments:
In `@relay/channel/openai/helper.go`:
- Around line 55-79: After unmarshalling in handleGeminiFormat and in the Gemini
branch of HandleFinalResponse, set the stream response's Model to the
client-facing name by assigning streamResponse.Model =
relaycommon.ResponseModelNameForClient(info) (or equivalent on the final
response struct) before converting to geminiResponse and before
marshalling/sending; ensure you perform this rewrite immediately after
common.Unmarshal and before calling service.StreamResponseOpenAI2Gemini (in
handleGeminiFormat) and before marshalling/sending in the Gemini final-response
path so Gemini clients see the client-requested model name just like Claude
paths.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 4db55220-01a7-4f17-86b0-0e89d9c8d341

📥 Commits

Reviewing files that changed from the base of the PR and between f2f3410 and 21c42ea.

📒 Files selected for processing (10)
  • relay/channel/claude/relay-claude.go
  • relay/channel/claude/relay_claude_test.go
  • relay/channel/gemini/relay-gemini.go
  • relay/channel/openai/chat_via_responses.go
  • relay/channel/openai/helper.go
  • relay/channel/openai/relay-openai.go
  • relay/common/response_model.go
  • setting/model_setting/global.go
  • web/src/components/settings/ModelSetting.jsx
  • web/src/pages/Setting/Model/SettingGlobalModel.jsx

Comment on lines +37 to +45
ResponseModelOriginalEnabled bool `json:"response_model_original_enabled"`
ThinkingModelBlacklist []string `json:"thinking_model_blacklist"`
ChatCompletionsToResponsesPolicy ChatCompletionsToResponsesPolicy `json:"chat_completions_to_responses_policy"`
}

// 默认配置
var defaultOpenaiSettings = GlobalSettings{
PassThroughRequestEnabled: false,
ResponseModelOriginalEnabled: true,

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.

⚠️ Potential issue | 🟡 Minor

Default true introduces a backward-incompatible behavior change for existing deployments.

With model mapping in effect, existing clients have been receiving the upstream/mapped model name in responses. After this PR is deployed, every existing instance will silently start returning the client-requested model name instead, which can break downstream consumers/log pipelines/billing-side reconciliations that key off response.model.

Consider defaulting ResponseModelOriginalEnabled to false so the new behavior is opt-in (and update the corresponding frontend defaults in web/src/components/settings/ModelSetting.jsx line 43 and web/src/pages/Setting/Model/SettingGlobalModel.jsx line 71 to match). If an opt-in default is intentional, please call this out in the PR description / release notes.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@setting/model_setting/global.go` around lines 37 - 45, The default for
ResponseModelOriginalEnabled currently set to true in defaultOpenaiSettings
causes a backward-incompatible change; change ResponseModelOriginalEnabled to
false in the GlobalSettings default (defaultOpenaiSettings) so the new behavior
is opt-in, and update the frontend default settings in the corresponding
ModelSetting.jsx and SettingGlobalModel.jsx components to the same false default
to keep UI and backend consistent; if keeping true was intentional, document it
clearly in the PR description/release notes instead.

@seefs001 seefs001 closed this Apr 25, 2026
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.

2 participants