Skip to content

修复: OpenAI格式请求转Claude时系统提示词拼接失败 - #3262

Closed
PoseidonLi0514 wants to merge 5403 commits into
QuantumNous:mainfrom
PoseidonLi0514:fix/openai-to-claude-system-prompt
Closed

修复: OpenAI格式请求转Claude时系统提示词拼接失败#3262
PoseidonLi0514 wants to merge 5403 commits into
QuantumNous:mainfrom
PoseidonLi0514:fix/openai-to-claude-system-prompt

Conversation

@PoseidonLi0514

@PoseidonLi0514 PoseidonLi0514 commented Mar 15, 2026

Copy link
Copy Markdown

问题: 当用户通过OpenAI格式(v1/chat/completions)发送请求,后端渠道为Claude时, ConvertOpenAIRequest返回dto.ClaudeRequest类型,但compatible_handler.go中 仅对dto.GeneralOpenAIRequest做类型断言,导致断言失败,系统提示词拼接逻辑被跳过。

修复: 将单一类型断言改为type switch,新增*dto.ClaudeRequest分支,
复用claude_handler.go中已验证的系统提示词拼接逻辑。

Summary by CodeRabbit

  • Improvements
    • Enhanced system prompt handling for Claude-compatible requests with new override capabilities.
    • Improved system prompt consistency and application across different AI request types, ensuring proper prompt augmentation in all scenarios.
    • Refined system message handling to support both string-based and structured message formats.

seefs001 and others added 30 commits February 6, 2026 21:57
fix: /v1/chat/completions -> /v1/responses json_schema
将散落在多个文件中的预扣费/结算/退款逻辑抽象为统一的 BillingSession 生命周期管理:

- 新增 BillingSettler 接口 (relay/common/billing.go) 避免循环引用
- 新增 FundingSource 接口 + WalletFunding / SubscriptionFunding 实现 (service/funding_source.go)
- 新增 BillingSession 封装预扣/结算/退款原子操作 (service/billing_session.go)
- 新增 SettleBilling 统一结算辅助函数,替换各 handler 中的 quotaDelta 模式
- 重写 PreConsumeBilling 为 BillingSession 工厂入口
- controller/relay.go 退款守卫改用 BillingSession.Refund()

修复的 Bug:
- 令牌额度泄漏:PreConsumeTokenQuota 成功但 DecreaseUserQuota 失败时未回滚
- 订阅退款遗漏:FinalPreConsumedQuota=0 但 SubscriptionPreConsumed>0 时跳过退款
- 订阅多扣费:subConsume 强制为 1 但 FinalPreConsumedQuota 不同步
- 退款路径不统一:钱包/订阅退款逻辑现统一由 FundingSource.Refund 分派
- Settle 部分失败保护:新增 fundingSettled 标记,资金来源提交后
  令牌调整失败不再导致 Refund 误退已结算的资金
- 订阅多扣费修复:trySubscription 传 subConsume 而非 preConsumedQuota
  给 preConsume,保证三者(amount/preConsume/FinalPreConsumedQuota)一致
- 令牌回滚错误记录:preConsume 中 funding 失败时令牌回滚错误不再丢弃
- 移除钱包路径死代码:用户额度不足的 strings.Contains 匹配不可能命中
- WalletFunding.Refund 不重试:IncreaseUserQuota 非幂等,重试会多退
…e recharge card tabs

- Defaulting to subscriptions when available and avoiding initial flash when no plans exist.
- Adjust the wide-screen layout to place wallet and invite sections side by side, simplify the subscription header and controls, and add padding to prevent card borders from clipping.
- Update related i18n strings by adding the new tab label and removing the obsolete subscription blurb.
…iption-card-when-no-plans

✨ refactor(wallet): Top-up layout to embed subscription plans into the recharge card tabs
…-session

refactor: 抽象统一计费会话 BillingSession
Add a lightweight active-subscription check to skip subscription pre-consume when none exist, reducing unnecessary transactions and locks. In the subscription UI, disable subscription-first options when no active plan is available, show the effective fallback to wallet with a clear notice, and distinguish “invalidated” from “expired” states. Update i18n strings across supported locales to reflect the new messages and status labels.
Aligns the error variable types in the subscription-first path so that quota fallback checks use the correct NewAPIError.
This prevents build failures and preserves the intended wallet fallback when subscription pre-consume returns an insufficient quota error.
Routes quota alerts through a subscription-specific check when billing from subscriptions, preventing wallet-based thresholds from triggering false warnings.
Updates the notification settings description and localization keys to clarify that both wallet and subscription balances are monitored.
…n-quota-notify

🔔 feat: Add subscription-aware quota notifications and update UI copy
…-preference-fallback

✨ chore: Improve subscription billing fallback and UI states
…tumNous#2881)

当上游为 AWS Bedrock 时,message_delta 的 usage 可能缺少 input_tokens、
cache_creation_input_tokens、cache_read_input_tokens 等字段,导致与原生
Anthropic 格式不一致。从 message_start 积累的 claudeInfo 中补全这些字段后
重新序列化,确保客户端收到一致的 usage 格式。
Modified the formatUserLogs function to include a startIdx parameter, allowing for more flexible log ID assignment. Updated calls to this function in GetLogByTokenId and GetUserLogs to pass the appropriate starting index.
feat: add Codex channel disclaimer (i18n, OpenAI terms)
feat: Force beta=true parameter for Anthropic channel
feat(oauth): implement custom OAuth provider
fix: Claude stream block index/type transitions
fix: add paragraph breaks between reasoning summary chunks
# Conflicts:
#	service/openaicompat/chat_to_responses.go
…t-stream

feat: channel test with stream=true
…fo-input-token

fix: 使用openai兼容接口调用部分渠道在最终端点为claude原生端点下还是走了openai扣减input_token的逻辑
fix: 补全 streaming message_delta 事件缺失的 input_tokens 和 cache 相关字段
…sponses

feat: /v1/messages -> /v1/responses
Calcium-Ion and others added 27 commits March 6, 2026 23:35
Introduce a billing display mode feature allowing users to toggle between price and ratio views. Update relevant components and hooks to support this new functionality, ensuring consistent pricing information is displayed across the application.
Add siteDisplayType prop across various pricing components to conditionally render pricing information based on the selected display type. This update enhances the user experience by ensuring that pricing details are accurately represented according to the chosen display mode, particularly for token-based views.
为渠道参数覆盖可视化规则提供拖拽排序支持
…4f8a4248b0ab3b03ba703796ea3

fix: kling risk fail return openAIVideo error
…ride-beta-header-append

feat:support $keep_only_declared and deduped $append for header override
chore: update model lists for frequently used channels
问题: 当用户通过OpenAI格式(v1/chat/completions)发送请求,后端渠道为Claude时,
ConvertOpenAIRequest返回*dto.ClaudeRequest类型,但compatible_handler.go中
仅对*dto.GeneralOpenAIRequest做类型断言,导致断言失败,系统提示词拼接逻辑被跳过。

修复: 将单一类型断言改为type switch,新增*dto.ClaudeRequest分支,
复用claude_handler.go中已验证的系统提示词拼接逻辑。
@coderabbitai

coderabbitai Bot commented Mar 15, 2026

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 49370398-9c72-4d4d-b239-4614b8d4528f

📥 Commits

Reviewing files that changed from the base of the PR and between 34893b0 and 6f67d1f.

📒 Files selected for processing (1)
  • relay/compatible_handler.go

Walkthrough

A type switch in compatible_handler.go replaces direct type assertion to differentiate handling of GeneralOpenAIRequest and ClaudeRequest, enabling system prompt detection and override logic tailored to each request format, including string and media message conversion for Claude.

Changes

Cohort / File(s) Summary
System Prompt Override Handler
relay/compatible_handler.go
Type switch replaces assertion to handle GeneralOpenAIRequest and ClaudeRequest separately. OpenAI requests detect missing system prompts and prepend or override within Messages. Claude requests initialize System field when nil and support override logic with string/media message format conversion.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • seefs001
  • Calcium-Ion

Poem

🐰 A rabbit hops through prompts with glee,
OpenAI and Claude, now unified thee,
System messages dance in type-switched delight,
Override the old, make the new shine bright!

🚥 Pre-merge checks | ✅ 2 | ❌ 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 (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is in Chinese and describes fixing system prompt concatenation for OpenAI-format requests converted to Claude format, which directly matches the PR objectives and changes made.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
📝 Coding Plan
  • Generate coding plan for human review comments

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.

Tip

CodeRabbit can generate a title for your PR based on the changes.

Add @coderabbitai placeholder anywhere in the title of your PR and CodeRabbit will replace it with a title based on the changes in the PR. You can change the placeholder by changing the reviews.auto_title_placeholder setting.

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.