Skip to content

渠道配置中增加使用ResponsesAPI开关以将OpenAI Compatible转换为OpenAI Responses请求 - #3175

Closed
raoczh wants to merge 5379 commits into
QuantumNous:mainfrom
raoczh:ready_push
Closed

渠道配置中增加使用ResponsesAPI开关以将OpenAI Compatible转换为OpenAI Responses请求#3175
raoczh wants to merge 5379 commits into
QuantumNous:mainfrom
raoczh:ready_push

Conversation

@raoczh

@raoczh raoczh commented Mar 8, 2026

Copy link
Copy Markdown

Summary by CodeRabbit

  • New Features
    • Added a per-channel Responses API toggle in channel configuration settings. Users can now enable or disable Responses API format conversion on individual channels, providing granular control over request handling at the channel level while maintaining compatibility with existing global configuration.

Calcium-Ion and others added 30 commits February 5, 2026 22:16
…al file types for LF normalization and binary detection
Mitigate XSS vulnerabilities in the playground where AI-generated content
is rendered without sanitization, allowing potential script injection via
prompt injection attacks.

MarkdownRenderer.jsx:
- Replace dangerouslySetInnerHTML with a sandboxed iframe for HTML preview
- Use sandbox="allow-same-origin" to block script execution while allowing
  CSS rendering and iframe height auto-sizing
- Add SandboxedHtmlPreview component with automatic height adjustment

CodeViewer.jsx:
- Add escapeHtml() utility to encode HTML entities before rendering
- Rewrite highlightJson() to process tokens iteratively, escaping each
  token and structural text before wrapping in syntax highlighting spans
- Escape non-JSON and very-large content paths that previously bypassed
  sanitization
- Update linkRegex to correctly match URLs containing & entities

These changes only affect the playground (AI output rendering). Admin-
configured content (home page, about page, footer, notices) remains
unaffected as they use separate code paths and are within the trusted
admin boundary.
🔒 fix(security): sanitize AI-generated HTML to prevent XSS in playground
…idation

- Add configurable per-user token creation limit (max_user_tokens)
- Sanitize search input patterns to prevent expensive queries
- Add per-user search rate limiting (by user ID)
- Add pagination to search endpoint with strict page size cap
- Skip empty search fields instead of matching nothing
- Hide internal errors from API responses
- Fix Interface2String float64 formatting causing config parse failures
- Add float-string fallback in config system for int/uint fields
fix: harden token search with pagination, rate limiting and input validation
- Change ESCAPE character from '\' to '!' for compatibility with MySQL/PostgreSQL/SQLite
- Adjust sanitization logic to escape '!' and '_' correctly, improving input validation for search queries
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 非幂等,重试会多退
nekohy and others added 26 commits March 5, 2026 06:12
…ide-wildcard-path

Feature/param override wildcard path
…7aec3eb60f27ca33dbb4dc9610a

fix: fetch model add header passthrough rule key check
feats: repair the thinking of claude to openrouter convert
…d958a777a7e7ac8c1e4b5b3e537

feat: kling cost quota support use FinalUnitDeduction as totalToken
…-top_p

fix: If top_p is not provided, Claude's logic will set to 1
…es-body-no-retry

fix(relay): skip retries for bad response body errors
Keep the model pricing editor wording aligned with the new price-based UI while exposing cache, image, and audio pricing in the marketplace so users can see the full configured pricing model.
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.
为渠道参数覆盖可视化规则提供拖拽排序支持
@coderabbitai

coderabbitai Bot commented Mar 8, 2026

Copy link
Copy Markdown
Contributor

Walkthrough

The PR introduces a per-channel UseResponsesAPI configuration flag that allows individual channels to opt into Responses API format conversion for chat completions. Changes span the backend DTO, relay handlers, frontend UI component, and localization strings.

Changes

Cohort / File(s) Summary
Backend Configuration
dto/channel_settings.go
Added UseResponsesAPI boolean field with json:"use_responses_api,omitempty" tag to ChannelSettings struct.
Relay Handler Logic
relay/claude_handler.go, relay/compatible_handler.go
Extended conditional checks in both handlers to trigger Responses API conversion when the per-channel UseResponsesAPI flag is true, in addition to the existing global gate.
Frontend UI & State
web/src/components/table/channels/modals/EditChannelModal.jsx
Added use_responses_api field to component state, form initialization, channel data parsing, and modal reset logic. Introduced Form.Switch UI element with label and helper text for toggling the setting.
Localization
web/src/i18n/locales/en.json
Added two new translation keys for the feature label and description in English.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

Suggested reviewers

  • seefs001

Poem

🐰 A switch for each channel, so fine and so neat,
The Responses API now makes the conversion complete!
Per-channel control, a flag shining bright,
Let handlers decide what feels just right. ✨

🚥 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 pull request title accurately describes the main change: adding a UseResponsesAPI configuration switch at the channel level to enable conversion of OpenAI-compatible requests to OpenAI Responses format, which is reflected across all modified files.

✏️ 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

Tip

Try Coding Plans. Let us write the prompt for your AI agent so you can ship faster (with fewer bugs).
Share your feedback on Discord.


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.

🧹 Nitpick comments (1)
web/src/components/table/channels/modals/EditChannelModal.jsx (1)

3882-3896: Only show this toggle on channel types that actually support Responses conversion.

Right now every channel can save use_responses_api, but this feature is scoped much narrower than “all channels”. Rendering it unconditionally makes unsupported types look configurable even if the relay path ignores the flag. Wrapping this switch in a supported-type check would avoid misleading config.

♻️ Suggested direction
+const RESPONSES_API_SUPPORTED_TYPES = new Set([
+  // keep this aligned with the backend handlers that honor `use_responses_api`
+  1,
+  14,
+]);
...
-                    <Form.Switch
-                      field='use_responses_api'
-                      label={t('使用 Responses API')}
-                      checkedText={t('开')}
-                      uncheckedText={t('关')}
-                      onChange={(value) =>
-                        handleChannelSettingsChange(
-                          'use_responses_api',
-                          value,
-                        )
-                      }
-                      extraText={t(
-                        '开启后,该渠道收到 chat/completions 请求时自动转换为 Responses API 格式发送给上游',
-                      )}
-                    />
+                    {RESPONSES_API_SUPPORTED_TYPES.has(inputs.type) && (
+                      <Form.Switch
+                        field='use_responses_api'
+                        label={t('使用 Responses API')}
+                        checkedText={t('开')}
+                        uncheckedText={t('关')}
+                        onChange={(value) =>
+                          handleChannelSettingsChange(
+                            'use_responses_api',
+                            value,
+                          )
+                        }
+                        extraText={t(
+                          '开启后,该渠道收到 chat/completions 请求时自动转换为 Responses API 格式发送给上游',
+                        )}
+                      />
+                    )}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@web/src/components/table/channels/modals/EditChannelModal.jsx` around lines
3882 - 3896, The Form.Switch for 'use_responses_api' is rendered unconditionally
(Form.Switch, field='use_responses_api', onChange ->
handleChannelSettingsChange), which exposes the toggle for channel types that
don't support Responses conversion; wrap this Form.Switch in a conditional that
checks the channel's type (e.g., channel.type or currentChannel.type) against
the explicit set of supported types (create a const like
SUPPORTED_RESPONSE_CONVERSION_TYPES or reuse an existing list) so the toggle
only renders when the channel type is in that set; keep the onChange handler
(handleChannelSettingsChange) and texts unchanged when visible.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@web/src/components/table/channels/modals/EditChannelModal.jsx`:
- Around line 3882-3896: The Form.Switch for 'use_responses_api' is rendered
unconditionally (Form.Switch, field='use_responses_api', onChange ->
handleChannelSettingsChange), which exposes the toggle for channel types that
don't support Responses conversion; wrap this Form.Switch in a conditional that
checks the channel's type (e.g., channel.type or currentChannel.type) against
the explicit set of supported types (create a const like
SUPPORTED_RESPONSE_CONVERSION_TYPES or reuse an existing list) so the toggle
only renders when the channel type is in that set; keep the onChange handler
(handleChannelSettingsChange) and texts unchanged when visible.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 8620f9ac-3e31-4f5a-8e82-11906a6b0dcd

📥 Commits

Reviewing files that changed from the base of the PR and between c706a5c and 77617cd.

📒 Files selected for processing (5)
  • dto/channel_settings.go
  • relay/claude_handler.go
  • relay/compatible_handler.go
  • web/src/components/table/channels/modals/EditChannelModal.jsx
  • web/src/i18n/locales/en.json

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.