Repository navigation
fix: Fix Openrouter test errors and optimize error messages - #2433
Conversation
WalkthroughAdded Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes
Possibly related PRs
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (4 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: 2
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
.gitignore(1 hunks)controller/channel-test.go(3 hunks)dto/error.go(2 hunks)types/error.go(4 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
controller/channel-test.go (2)
model/channel.go (1)
Channel(21-58)constant/channel.go (1)
ChannelTypeOpenRouter(24-24)
🔇 Additional comments (7)
.gitignore (1)
25-25: LGTM!Adding
.gomodcache/to the ignore list is appropriate for excluding the Go module cache from version control.dto/error.go (2)
3-7: LGTM!Import addition for
encoding/jsonis correctly scoped for the newjson.RawMessagetype usage.
28-28: LGTM!Adding
Metadata json.RawMessagewithomitemptyis appropriate for capturing optional upstream error metadata from providers like OpenRouter.controller/channel-test.go (2)
179-179: LGTM!Call site correctly updated to pass the channel parameter to enable channel-type-specific request building.
392-392: LGTM!Function signature appropriately extended to accept the channel parameter for type-specific logic.
types/error.go (2)
14-18: LGTM!Adding the
Metadatafield withomitemptytoOpenAIErrorproperly captures optional upstream metadata from providers like OpenRouter.
97-97: LGTM!Adding
MetadatatoNewAPIErrorenables metadata propagation through the error handling chain.
| if channel.Type == constant.ChannelTypeOpenRouter { | ||
| maxTokens = uint(16) | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🌐 Web query:
OpenRouter API max_tokens parameter requirements documentation
💡 Result:
Summary of OpenRouter's max_tokens requirements:
- Parameter: max_tokens — integer, optional. Minimum 1. It sets the upper limit of tokens the model can generate. [1]
- Upper bound: cannot exceed the model's context length minus the prompt/input length (i.e., available remaining context / model-specific max completion tokens). [1][3]
- For models that support separate reasoning token budgets, reasoning.max_tokens may apply and has provider-specific minima/limits (e.g., Anthropic reasoning.max_tokens uses a minimum of 1024 and is capped at 32,000; reasoning tokens must be smaller than max_tokens so response tokens remain). See provider notes. [2]
Sources: OpenRouter API parameters and reasoning docs. [1][2][3]
References
[1] OpenRouter API parameters (Max Tokens). (openrouter.ai)
[2] OpenRouter reasoning / reasoning.max_tokens details (Anthropic example). (openrouter.ai)
[3] OpenRouter models / model context & max_completion_tokens. (openrouter.hconeai.com)
Citations:
- 1: https://openrouter.ai/docs/api/reference/parameters?utm_source=openai
- 2: https://openrouter.ai/docs/use-cases/reasoning-tokens?utm_source=openai
- 3: https://openrouter.hconeai.com/docs/overview/models?utm_source=openai
🏁 Script executed:
cd controller && sed -n '420,450p' channel-test.goRepository: QuantumNous/new-api
Length of output: 850
This is test code—the MaxTokens override is acceptable but document the reason.
The value of 16 is valid for OpenRouter (API minimum is 1 with no fixed upper limit per request). However, since this appears to be test code creating mock requests for different channel types, clarify whether this value is intentionally chosen for test differentiation (to distinguish OpenRouter behavior from default 10 and Gemini's 3000) or if it represents an actual requirement. If it's for test isolation, add a brief comment explaining this.
🤖 Prompt for AI Agents
In controller/channel-test.go around lines 430 to 432, the test sets maxTokens
to 16 for ChannelTypeOpenRouter without any explanation; add a brief inline
comment above this assignment stating that 16 is deliberately chosen for test
isolation/differentiation (e.g., to distinguish OpenRouter behaviour from the
default 10 and Gemini's 3000) so readers know it’s a test-only value and not a
production requirement.
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (1)
types/error.go (1)
280-310: OpenRouter metadata formatting +e.Errreassign are correctly fixed.
This addresses the prior%v/byte-slice formatting and keepsError()consistent with the mutatedRelayError.Message.
🧹 Nitpick comments (1)
types/error.go (1)
89-98:NewAPIError.Metadatais OK; consider documenting intended propagation.
Right nowNewAPIError.Metadatais a parallel field that may or may not be reflected byToOpenAIError()depending onRelayError; a short comment (or ensuring consistent propagation) would prevent future misuse.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
types/error.go(4 hunks)
🔇 Additional comments (3)
types/error.go (3)
3-11:encoding/jsonimport forjson.RawMessageis appropriate.
No concerns here;json.RawMessageis the right type for pass-through JSON blobs.
13-19:OpenAIError.Metadatacontains provider-supplied JSON—ensure it's not logged or exposed without redaction.Since
json.RawMessagemay contain API tokens, user prompts, PII, or other sensitive data from the provider, verify that downstream code (logging, error responses, serialization) does not exposeMetadatadirectly to users or logs. IfMetadatais user-facing or logged, implement field-level redaction, truncation, or an allowlist of safe fields before returning it.
299-305: Consider truncating or sanitizing metadata before appending toMessageand exposing via DTO.Metadata can bloat responses and expose sensitive information (internal IDs, tokens, debug details). Per security best practices, untrusted or unvetted metadata should be truncated, redacted, or limited to debug-only logging. Ensure the DTO schema enforces a whitelist of safe fields.
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (2)
controller/channel-test.go (2)
179-179: Thechannelparameter is passed but unused inbuildTestRequest.The
channelargument is passed tobuildTestRequestbut is never referenced within the function body. If this parameter is intended for future channel-specific request customization (e.g., adjustingmaxTokensbased on channel type or settings), consider adding a TODO comment. Otherwise, remove it to avoid confusion.
392-441: Unusedchannelparameter in function signature.The
channel *model.Channelparameter is declared but never used withinbuildTestRequest. If channel-specific logic (e.g., per-channel token limits or custom test payloads) is planned, add a TODO comment. Otherwise, remove the parameter to keep the signature clean.Regarding the
maxTokens = 16change on line 426: this aligns with the previous review feedback confirming that 16 is valid for OpenRouter's API requirements and addresses the PR objective of fixing OpenRouter test errors. As noted in the past review, documenting the rationale (e.g., "16 chosen to meet OpenRouter minimum and differentiate from default 10") would improve clarity for future maintainers.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
controller/channel-test.go(3 hunks)
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2025-06-18T12:20:25.779Z
Learnt from: neotf
Repo: QuantumNous/new-api PR: 1120
File: service/quota.go:0-0
Timestamp: 2025-06-18T12:20:25.779Z
Learning: For OpenRouter integration: cacheTokens returned from upstream always belong to [0, promptTokens], meaning cacheTokens will never exceed the original promptTokens value. This constraint ensures that operations like `promptTokens -= cacheTokens` will not result in negative values.
Applied to files:
controller/channel-test.go
📚 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:
controller/channel-test.go
🧬 Code graph analysis (1)
controller/channel-test.go (2)
model/channel.go (1)
Channel(21-58)dto/request_common.go (1)
Request(8-12)
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (3)
controller/channel-test.go (3)
184-184: The channel parameter is unused.The
channelparameter was added tobuildTestRequestat line 397 but is never referenced in the function body. Either use the parameter for channel-specific request customization or remove it to avoid confusion.Apply this diff if the parameter is not needed:
-func buildTestRequest(model string, endpointType string, channel *model.Channel) dto.Request { +func buildTestRequest(model string, endpointType string) dto.Request {And update the call site:
- request := buildTestRequest(testModel, endpointType, channel) + request := buildTestRequest(testModel, endpointType)Also applies to: 397-486
474-474: Document the MaxCompletionTokens increase to 16.For models starting with "o" (reasoning models like o1, o3), the
MaxCompletionTokenswas increased from 10 to 16. Please add a brief inline comment explaining why 16 is chosen, especially since these are reasoning models that may have different token requirements.
482-482: Document the default MaxTokens increase to 16.The default
MaxTokensvalue was increased from 10 to 16, consistent with the changes at lines 431 and 474. As noted in a previous review, since this relates to fixing OpenRouter test errors (per PR objectives), please add a brief inline comment explaining that 16 is the minimum value that works reliably across providers, or whatever the specific rationale is.Example documentation:
} else { + // Use 16 as minimum to ensure compatibility with OpenRouter and other providers testRequest.MaxTokens = 16 }
📜 Review details
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
controller/channel-test.go(5 hunks)
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2025-06-18T12:20:25.779Z
Learnt from: neotf
Repo: QuantumNous/new-api PR: 1120
File: service/quota.go:0-0
Timestamp: 2025-06-18T12:20:25.779Z
Learning: For OpenRouter integration: cacheTokens returned from upstream always belong to [0, promptTokens], meaning cacheTokens will never exceed the original promptTokens value. This constraint ensures that operations like `promptTokens -= cacheTokens` will not result in negative values.
Applied to files:
controller/channel-test.go
📚 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:
controller/channel-test.go
🔇 Additional comments (2)
controller/channel-test.go (2)
100-104: LGTM! Codex model endpoint routing added correctly.The codex-specific path routing to
/v1/responsesis consistent with theEndpointTypeOpenAIResponsehandling andRelayFormatOpenAIResponsesdetection elsewhere in the file.
431-431: No changes required. This code is a test fixture builder (buildTestRequest) that creates mock requests for channel testing purposes, not production code affecting actual API calls. ThemaxTokensvalue of 16 is an arbitrary test value used only for testing endpoint connectivity; it does not impact real provider behavior or interactions. Different endpoint types intentionally use different test values (16 for OpenAI/Anthropic, 3000 for Gemini) purely for testing purposes.Likely an incorrect or invalid review comment.
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (1)
controller/channel-test.go (1)
431-431: Token value change lacks documentation (see past review).The
maxTokensvalue changed from 10 to 16. A previous reviewer already noted that this value should be documented to clarify whether it's a test-specific value or represents an actual requirement.Based on the past review comment, add a brief inline comment explaining why 16 is chosen (e.g., to ensure compatibility with OpenRouter or to differentiate test behavior).
📜 Review details
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
controller/channel-test.go(6 hunks)
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2025-06-18T12:20:25.779Z
Learnt from: neotf
Repo: QuantumNous/new-api PR: 1120
File: service/quota.go:0-0
Timestamp: 2025-06-18T12:20:25.779Z
Learning: For OpenRouter integration: cacheTokens returned from upstream always belong to [0, promptTokens], meaning cacheTokens will never exceed the original promptTokens value. This constraint ensures that operations like `promptTokens -= cacheTokens` will not result in negative values.
Applied to files:
controller/channel-test.go
📚 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:
controller/channel-test.go
🧬 Code graph analysis (1)
controller/channel-test.go (3)
model/channel.go (1)
Channel(21-58)dto/request_common.go (1)
Request(8-12)dto/openai_request.go (2)
OpenAIResponsesRequest(792-817)Input(901-905)
🔇 Additional comments (3)
controller/channel-test.go (3)
100-104: LGTM - Codex model routing added correctly.The codex model detection and routing to
/v1/responsesis implemented correctly and aligns with the PR objective to fix OpenRouter test errors. The case-insensitive matching is appropriate.
461-467: LGTM - Codex handling is consistent and correct.The codex model detection properly returns an
OpenAIResponsesRequest, which aligns with the path routing logic added in lines 100-104. This addresses the PR objective to fix OpenRouter test errors.
482-490: Token values increased consistently across test cases.The default token values changed from 10 to 16 for both
MaxCompletionTokens(line 482) andMaxTokens(line 490). This is consistent with the change on line 431 and likely helps avoid test failures with providers that have minimum token requirements.
| } | ||
|
|
||
| request := buildTestRequest(testModel, endpointType) | ||
| request := buildTestRequest(testModel, endpointType, channel) |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major
Remove unused channel parameter or document its future purpose.
The channel parameter is passed to buildTestRequest but is never used within that function (lines 397-494). This is dead code.
If the parameter is needed for future enhancements, add a comment explaining its purpose. Otherwise, remove it:
-request := buildTestRequest(testModel, endpointType, channel)
+request := buildTestRequest(testModel, endpointType)And update the function signature accordingly (see comment on line 397).
Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In controller/channel-test.go around line 184 (and update function at 397-494),
the call passes a `channel` argument to buildTestRequest but the parameter is
unused; either remove the parameter from the call and from buildTestRequest's
signature (and any other call sites), or if it must be retained for future use
add a clear comment on the buildTestRequest parameter explaining its intended
future purpose and keep the signature but avoid compiler unused warnings; after
making the change, update all call sites, run `go vet`/`go build` and tests to
ensure no references remain and commit the updated function signature or the
documented parameter.
| } | ||
|
|
||
| func buildTestRequest(model string, endpointType string) dto.Request { | ||
| func buildTestRequest(model string, endpointType string, channel *model.Channel) dto.Request { |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major
Remove unused channel parameter from function signature.
The channel parameter is declared but never used in the function body. This creates unnecessary coupling and confusion.
Apply this diff to remove the unused parameter:
-func buildTestRequest(model string, endpointType string, channel *model.Channel) dto.Request {
+func buildTestRequest(model string, endpointType string) dto.Request {Also update the call site on line 184.
Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In controller/channel-test.go around line 397, the function buildTestRequest
declares an unused parameter `channel *model.Channel`; remove `channel` from the
function signature and any reference in its declaration so it becomes
buildTestRequest(model string, endpointType string) dto.Request, then locate the
call site on line 184 and remove the corresponding argument (the Channel value)
from that call so the call matches the new two-parameter signature;
rebuild/tests to ensure no other call sites need updating.
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (2)
controller/channel-test.go (2)
184-184: Remove unusedchannelparameter.The
channelparameter passed tobuildTestRequestis never used within the function body (lines 407-504). This was previously flagged and remains unaddressed.
407-407: Remove unusedchannelparameter from function signature.The
channelparameter is declared but never referenced in the function body. This was previously flagged and should be removed along with updating the call site at line 184.
🧹 Nitpick comments (3)
controller/channel-test.go (3)
441-441: Document the test-specific MaxTokens value.The value of 16 is valid, but as mentioned in previous reviews, this test-specific value should be documented. Add a brief inline comment explaining why 16 is chosen for test differentiation (e.g., to distinguish from the previous default of 10 and Gemini's 3000).
Suggested documentation
case constant.EndpointTypeAnthropic, constant.EndpointTypeGemini, constant.EndpointTypeOpenAI: // 返回 GeneralOpenAIRequest + // Use 16 tokens for test requests (valid minimum for OpenRouter/OpenAI, distinguishes from previous default of 10) maxTokens := uint(16)
492-492: Consider documenting the MaxCompletionTokens value.Similar to the MaxTokens change at line 441, this test-specific value change from 10 to 16 would benefit from a brief inline comment explaining the choice for reasoning models (those starting with "o").
500-500: Consider documenting the default MaxTokens value.This is the default MaxTokens value for general test requests. As with the other token value changes in this PR (lines 441, 492), adding a brief comment explaining the choice of 16 would improve code clarity.
📜 Review details
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
controller/channel-test.go(7 hunks)
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2025-06-18T12:20:25.779Z
Learnt from: neotf
Repo: QuantumNous/new-api PR: 1120
File: service/quota.go:0-0
Timestamp: 2025-06-18T12:20:25.779Z
Learning: For OpenRouter integration: cacheTokens returned from upstream always belong to [0, promptTokens], meaning cacheTokens will never exceed the original promptTokens value. This constraint ensures that operations like `promptTokens -= cacheTokens` will not result in negative values.
Applied to files:
controller/channel-test.go
📚 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:
controller/channel-test.go
🧬 Code graph analysis (1)
controller/channel-test.go (4)
common/sys_log.go (1)
SysError(16-19)model/channel.go (1)
Channel(21-58)dto/request_common.go (1)
Request(8-12)dto/openai_request.go (2)
OpenAIResponsesRequest(792-817)Input(901-905)
🔇 Additional comments (3)
controller/channel-test.go (3)
327-336: LGTM! Enhanced error logging aids debugging.The detailed error logging captures all relevant context (channel ID, name, type, model, endpoint type, status, and error) which directly supports the PR objective of diagnosing OpenRouter test failures.
471-477: LGTM! Codex model handling is correctly implemented.The codex detection logic properly constructs an
OpenAIResponsesRequestwith appropriate fields. The implementation is consistent with the routing logic added at lines 100-104.
100-104: No action required. The code correctly routes Codex models to the/v1/responsesendpoint, which OpenRouter supports for this model family.
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
service/error.go (1)
103-125: Limit response body length in error messages to prevent unwieldy error strings.io.ReadAll doesn't impose limits on data - if called on a very large stream, it will keep reading and allocating memory until it finishes or the system runs out. Currently, the full
responseBodyfrom line 87 is included in all error messages created bybuildErrWithBody(lines 103, 117, 124) without any truncation. Consider limiting the body to a reasonable length (e.g., 2KB) before including it in error messages.Verify showBodyWhenFail is set correctly in production and fix line 105 security bypass.
The
showBodyWhenFailflag gates whether the body is included in error objects, but line 105 logs the full body vialogger.LogError()even when the flag is false. This bypasses the intended security protection. RESTful web services should prevent leaking credentials - passwords, security tokens, and API keys should not appear in logs. Either apply the sameshowBodyWhenFailcheck before logging at line 105, or truncate the body there as well.
📜 Review details
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
service/error.go(2 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
service/error.go (2)
common/json.go (1)
Unmarshal(9-11)types/error.go (2)
NewOpenAIError(229-252)ErrorCodeBadResponseStatusCode(72-72)
🔇 Additional comments (1)
service/error.go (1)
93-98: LGTM! Clean refactoring to reduce duplication.The helper function effectively centralizes error message construction with response body inclusion, eliminating code duplication across multiple error handling paths.
…ous#2433) * fix: Refine openrouter error * fix: Refine openrouter error * fix: openrouter test max_output_token * fix: optimize messages * fix: maxToken unified to 16 * fix: codex系列模型使用 responses接口 * fix: codex系列模型使用 responses接口 * fix: 状态码非200打印错误信息 * fix: 日志里没有报错的响应体
…ous#2433) * fix: Refine openrouter error * fix: Refine openrouter error * fix: openrouter test max_output_token * fix: optimize messages * fix: maxToken unified to 16 * fix: codex系列模型使用 responses接口 * fix: codex系列模型使用 responses接口 * fix: 状态码非200打印错误信息 * fix: 日志里没有报错的响应体
…ous#2433) * fix: Refine openrouter error * fix: Refine openrouter error * fix: openrouter test max_output_token * fix: optimize messages * fix: maxToken unified to 16 * fix: codex系列模型使用 responses接口 * fix: codex系列模型使用 responses接口 * fix: 状态码非200打印错误信息 * fix: 日志里没有报错的响应体
fix #2432
测试渠道场景会完整返回请求上游返回的错误信息
Summary by CodeRabbit
Bug Fixes
New Features
Chores
✏️ Tip: You can customize this high-level summary in your review settings.