Repository navigation
Go: implement provider: OpenRouter - #14652
Conversation
📝 WalkthroughWalkthroughAdds OpenRouter as a new model provider with full chat, streaming, and reranking support. Hardens region-selection logic across 13 providers to validate non-empty region strings. Refactors thinking-content extraction in four providers to use direct field access instead of helper functions. Removes unused Chat method from Minimax. ChangesOpenRouter Integration and Provider Hardening
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. 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: 18
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (8)
internal/entity/models/gitee.go (1)
244-278:⚠️ Potential issue | 🟠 Major | ⚡ Quick win
chatModelConfigis dereferenced without a nil guardThere is no
if chatModelConfig != nilcheck before accessingchatModelConfig.Stream,chatModelConfig.MaxTokens, etc. at lines 244 onwards. If the caller passesnil, this panics at line 244. Compare withChatWithMessages(line 97) and DeepSeek'sChatStreamlyWithSender, both of which wrap the config block with a nil check.🐛 Proposed fix
- if chatModelConfig.Stream != nil { + if chatModelConfig != nil && chatModelConfig.Stream != nil {Or wrap the entire block:
+ if chatModelConfig != nil { if chatModelConfig.Stream != nil { reqBody["stream"] = *chatModelConfig.Stream } // ... rest of chatModelConfig accesses ... + }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/gitee.go` around lines 244 - 278, The block that dereferences chatModelConfig (checking Stream, MaxTokens, Temperature, DoSample, TopP, Stop, Thinking) should be guarded by a nil check to avoid panics when callers pass nil; wrap the existing sequence that sets entries on reqBody inside an if chatModelConfig != nil { ... } so all references to chatModelConfig (in gitee.go where reqBody is populated) only occur when chatModelConfig is non-nil, preserving the existing per-field nil checks and the Thinking handling.internal/entity/models/moonshot.go (1)
231-265:⚠️ Potential issue | 🟠 Major | ⚡ Quick win
chatModelConfigis accessed without a nil guardLine 231 (
if chatModelConfig.Stream != nil) will panic if the caller passesnilforchatModelConfig. There is no enclosingif chatModelConfig != nilcheck. This is the same structural gap asgitee.goandaliyun.go.🐛 Proposed fix
+ if chatModelConfig != nil { if chatModelConfig.Stream != nil { reqBody["stream"] = *chatModelConfig.Stream } // ... remaining chatModelConfig field accesses ... + }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/moonshot.go` around lines 231 - 265, The code reads fields from chatModelConfig without checking for nil, which can panic; add a top-level nil guard (if chatModelConfig != nil) around the entire block that accesses chatModelConfig.Stream, MaxTokens, Temperature, DoSample, TopP, Stop, and Thinking so none of those dereferences occur when chatModelConfig is nil, preserving the existing behavior for each field inside that guarded block.internal/entity/models/aliyun.go (1)
228-258:⚠️ Potential issue | 🟠 Major | ⚡ Quick win
chatModelConfigis accessed without a nil guardLine 228 (
if chatModelConfig.Stream != nil) will panic ifchatModelConfigisnil. Same structural issue asgitee.goandmoonshot.go.🐛 Proposed fix
+ if chatModelConfig != nil { if chatModelConfig.Stream != nil { reqBody["stream"] = *chatModelConfig.Stream } // ... remaining chatModelConfig accesses ... + }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/aliyun.go` around lines 228 - 258, The code accesses chatModelConfig fields directly and will panic when chatModelConfig is nil; wrap the entire block that sets reqBody["stream"/"max_tokens"/.../"enable_thinking"] in a nil guard (e.g., if chatModelConfig != nil { ... }) or otherwise early-return/skip this section when chatModelConfig is nil so that references like chatModelConfig.Stream, MaxTokens, Temperature, DoSample, TopP, Stop, and Thinking are only dereferenced when chatModelConfig is non-nil.internal/entity/models/deepseek.go (1)
285-312:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winNil dereference on
chatModelConfig.Effortwhen thinking is enabled
switch *chatModelConfig.Effortat line 288 panics ifEffortisnil. The non-streamingChatWithMessagescounterpart correctly guards this with a nil check and a hardcoded default:effort := "high" if chatModelConfig.Effort != nil { effort = *chatModelConfig.Effort }The streaming path must do the same. The current
default: return fmt.Errorf("invalid effort level")also diverges fromChatWithMessageswhich silently uses the effort value — consider aligning both paths.🐛 Proposed fix
if chatModelConfig.Thinking != nil { if *chatModelConfig.Thinking { var thinkingFlag string - switch *chatModelConfig.Effort { + effort := "high" + if chatModelConfig.Effort != nil { + effort = *chatModelConfig.Effort + } + switch effort { case "none": thinkingFlag = "disabled" - break case "low": thinkingFlag = "disabled" - break case "medium": thinkingFlag = "disabled" - break case "high": thinkingFlag = "enabled" reqBody["reasoning_effort"] = "high" - break case "default": thinkingFlag = "enabled" reqBody["reasoning_effort"] = "high" - break case "max": thinkingFlag = "enabled" reqBody["reasoning_effort"] = "max" - break default: - return fmt.Errorf("invalid effort level") + thinkingFlag = "enabled" + reqBody["reasoning_effort"] = effort }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/deepseek.go` around lines 285 - 312, The streaming branch dereferences chatModelConfig.Effort without a nil check (switch *chatModelConfig.Effort) causing a panic; change to read a local effort string with a default (e.g., "high") like the non-streaming ChatWithMessages path (set effort := "high" and if chatModelConfig.Effort != nil then effort = *chatModelConfig.Effort), then switch on that local effort variable instead of *chatModelConfig.Effort; also align behavior by removing the default return error and handle unknown values consistently with ChatWithMessages while still setting reqBody["reasoning_effort"] and thinkingFlag for "high","default","max" cases.internal/entity/models/volcengine.go (1)
70-72:⚠️ Potential issue | 🟠 Major | ⚡ Quick win
Chatmethod region guard was not updated — inconsistent with the other three methods in this file
ChatWithMessages,ChatStreamlyWithSender, andCheckConnectionall received the*apiConfig.Region != ""guard, but theChatmethod at line 70 still uses the nil-only check. The same empty-string region can still cause anunsupported protocol scheme ""error whenChatis called.🔧 Proposed fix
- if apiConfig.Region != nil { + if apiConfig.Region != nil && *apiConfig.Region != "" { region = *apiConfig.Region }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/volcengine.go` around lines 70 - 72, In the Chat method, the region nil-check is inconsistent with ChatWithMessages, ChatStreamlyWithSender, and CheckConnection—update the guard that sets the local region so it verifies both that apiConfig.Region is non-nil and that *apiConfig.Region is not an empty string (e.g., replace the current nil-only check with a combined non-nil && non-empty check) so the region variable is only set when apiConfig.Region contains a non-empty value; refer to the Chat method and the apiConfig.Region and region variables when making this change to match the other methods' behavior.internal/entity/models/openai.go (1)
102-105:⚠️ Potential issue | 🟠 Major | ⚡ Quick win
ChatWithMessagesandListModelsregion guards are not updated — inconsistent within this file
ChatStreamlyWithSendernow guards against an empty-string region, butChatWithMessages(line 103) andListModels(line 421) still assignregion = *apiConfig.Regionwhenever the pointer is non-nil. Passing an empty string from the UI still passes""tobaseURLForRegion, which returns an error. While that error is at least surfaced explicitly (thanks tobaseURLForRegion), the behaviour is inconsistent with the streaming path and the fix intent.🔧 Proposed fix for both methods
- if apiConfig.Region != nil { + if apiConfig.Region != nil && *apiConfig.Region != "" { region = *apiConfig.Region }Apply the same to
ListModels(line 421).🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/openai.go` around lines 102 - 105, ChatWithMessages and ListModels still set region directly from apiConfig.Region when non-nil, allowing empty strings to be passed to baseURLForRegion; update both methods to mirror ChatStreamlyWithSender by assigning region only when apiConfig.Region is non-nil AND the pointed string is non-empty (e.g., check apiConfig.Region != nil && *apiConfig.Region != "" before setting region = *apiConfig.Region) so baseURLForRegion never receives an empty region.internal/entity/models/lmstudio.go (1)
65-68:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winRegion empty-string fix missing in
ChatWithMessages.
ChatStreamlyWithSender(Line 209) andListModels(Line 375) were updated to gate on*apiConfig.Region != "", butChatWithMessageshere still uses the looserapiConfig.Region != nilcheck and will still hit the original "unsupported protocol scheme" bug when the UI passes an empty region. It also dereferencesapiConfigwithout a nil check.🛡️ Suggested fix
var region = "default" - if apiConfig.Region != nil { + if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" { region = *apiConfig.Region }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/lmstudio.go` around lines 65 - 68, ChatWithMessages currently sets region using only apiConfig.Region != nil and dereferences apiConfig without checking nil, which allows an empty-string region to slip through; update the region determination in ChatWithMessages to first ensure apiConfig != nil, then check apiConfig.Region != nil && *apiConfig.Region != "" and only then set region = *apiConfig.Region, otherwise keep region = "default" (mirror the guard used in ChatStreamlyWithSender and ListModels) to avoid the unsupported protocol scheme bug.internal/entity/models/ollama.go (1)
64-67:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winRegion guard fix missing in
ChatWithMessagesandListModels.The PR description states the empty-string region bug is fixed across the codebase to prevent
unsupported protocol scheme ""errors, but in this file onlyChatStreamlyWithSender(Line 207) was updated.ChatWithMessages(Lines 64-67) andListModels(Lines 371-375) still use the oldapiConfig.Region != nilcheck and will still produceo.BaseURL[""]→ empty URL when the UI sends an empty region string. Additionally, both methods dereferenceapiConfigwithout a nil check, so a nil config will panic.🛡️ Suggested fix
var region = "default" - if apiConfig.Region != nil { + if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" { region = *apiConfig.Region }Apply the same change at Lines 371-375 in
ListModels.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/ollama.go` around lines 64 - 67, The region handling in ChatWithMessages and ListModels is still using the old apiConfig.Region != nil check and also dereferences apiConfig without a nil guard, which allows an empty-string region or nil config to produce empty BaseURL access or a panic; update both ChatWithMessages and ListModels to mirror ChatStreamlyWithSender by first checking apiConfig != nil, then treating an empty or nil Region as "default" (e.g., set region := "default"; if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" { region = *apiConfig.Region }), and then use that region when accessing o.BaseURL[region].
🧹 Nitpick comments (7)
internal/entity/models/aliyun.go (1)
382-384: ⚡ Quick win
ListModelsregion guard not updated
CheckConnectioncallsListModels; an empty-string region from the UI still bypasses the fix here.🔧 Proposed fix
- if apiConfig.Region != nil { + if apiConfig.Region != nil && *apiConfig.Region != "" { region = *apiConfig.Region }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/aliyun.go` around lines 382 - 384, ListModels still treats a nil Region pointer as the only "unset" case, so an empty-string region from the UI slips through; update the guard in ListModels (the block that currently reads if apiConfig.Region != nil { region = *apiConfig.Region }) to treat empty or whitespace-only strings as unset—e.g., check apiConfig.Region != nil && strings.TrimSpace(*apiConfig.Region) != "" before assigning to region—so CheckConnection and other callers won't proceed with an empty region.internal/entity/models/gitee.go (1)
410-414: ⚡ Quick win
ListModels,Balance, andCheckConnectionare not covered by this fixAll three still use
if apiConfig.Region != nilwithout the empty-string check, so theunsupported protocol scheme ""error can still occur when these paths are exercised (e.g.,CheckConnectionis triggered directly from the UI).🔧 Proposed fix (same pattern for all three)
- if apiConfig.Region != nil { + if apiConfig.Region != nil && *apiConfig.Region != "" { region = *apiConfig.Region }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/gitee.go` around lines 410 - 414, The three methods ListModels, Balance, and CheckConnection currently only check for apiConfig.Region != nil and can still use an empty string as the region (causing unsupported protocol scheme ""), so update each method (ListModels, Balance, CheckConnection on type GiteeModel) to validate apiConfig.Region by checking both that it is non-nil and that *apiConfig.Region != "" before assigning it to region; leave the default region value when the pointer is nil or the string is empty and ensure all uses of region in those functions rely on the validated value.internal/entity/models/deepseek.go (1)
434-437: ⚡ Quick win
ListModelsregion guard not updated — same bug still present in this path
CheckConnectiondelegates toListModels, which still uses the nil-only guard. If the UI passes an empty-string region,CheckConnectionwill still hit the""key in the map (producing an empty base URL and the sameunsupported protocol scheme ""error the PR intends to fix).🔧 Proposed fix
- if apiConfig.Region != nil { + if apiConfig.Region != nil && *apiConfig.Region != "" { region = *apiConfig.Region }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/deepseek.go` around lines 434 - 437, In ListModels update the region guard to treat both nil and empty-string the same as the other path: if apiConfig.Region is nil OR *apiConfig.Region == "" set region = "default" so CheckConnection (which calls ListModels) no longer allows an empty-string region to be used as a map key; locate the region variable and the ListModels function in internal/entity/models/deepseek.go and apply the same empty-string check you used elsewhere where apiConfig.Region is validated.internal/entity/models/moonshot.go (1)
366-369: ⚡ Quick win
ListModelsandBalanceare not covered by the region-fixBoth still use
if apiConfig.Region != nilwithout the empty-string check, soCheckConnection(which delegates toListModels) can still produce an empty base URL.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/moonshot.go` around lines 366 - 369, ListModels and Balance still accept apiConfig.Region when it's non-nil but empty, causing an empty base URL in CheckConnection; update both functions (ListModels and Balance) to treat nil or empty-string regions the same as omitted by initializing region := "default" and only override it when apiConfig.Region != nil && *apiConfig.Region != "" so the region fallback is applied and no empty base URL is produced.internal/entity/models/zhipu-ai.go (1)
368-370: ⚡ Quick win
EncodeandRerankregion guards not updated
Encode(line 368) andRerank(line 529) still use the nil-only check. An empty-string region would be used as a map key, returning an empty base URL.🔧 Proposed fix (same for both)
- if apiConfig.Region != nil { + if apiConfig.Region != nil && *apiConfig.Region != "" { region = *apiConfig.Region }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/zhipu-ai.go` around lines 368 - 370, The region guard in Encode and Rerank currently only checks for nil so an empty-string region ends up being used as a map key; update both guards (where apiConfig.Region and region are handled in Encode and Rerank) to require a non-empty string as well (i.e., check apiConfig.Region != nil AND *apiConfig.Region != "" before assigning region) so empty-string regions do not override the default base URL lookup.internal/entity/models/siliconflow.go (1)
476-478: ⚡ Quick win
ListModels(and thereforeCheckConnection) are not guardedThe same empty-string region bug can still surface when
CheckConnectioninvokesListModels.🔧 Proposed fix
- if apiConfig.Region != nil { + if apiConfig.Region != nil && *apiConfig.Region != "" { region = *apiConfig.Region }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/siliconflow.go` around lines 476 - 478, ListModels (and callers like CheckConnection) can be invoked with apiConfig.Region unset causing an empty-string region; ensure ListModels never runs with an empty region by validating/normalizing apiConfig.Region before calling or inside ListModels: in the CheckConnection path and any caller that uses the local variable region (the code that reads apiConfig.Region into region), check for nil or empty string and either set a safe default or return a clear error, and add the same guard at the start of ListModels to validate the region parameter so ListModels itself refuses to operate with an empty region; update the code paths referencing apiConfig.Region and the local region variable to use this normalized value.internal/entity/models/xai.go (1)
100-110: ⚡ Quick winInconsistent region guard between methods.
ChatStreamlyWithSender(Line 237) andListModels(Line 413) now requireapiConfig.Region != nil && *apiConfig.Region != "", butChatWithMessages(Lines 102-104) was left with the looser nil-only check. The fall-through tobaseURLForRegionwill still error out on an unknown empty key, but the error message is clearer when the empty-string case is normalized to"default"consistently.♻️ Suggested fix
var region = "default" - if apiConfig.Region != nil { + if apiConfig.Region != nil && *apiConfig.Region != "" { region = *apiConfig.Region }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/xai.go` around lines 100 - 110, The region check in ChatWithMessages is looser than other methods; update its guard to match ChatStreamlyWithSender and ListModels by treating an empty-region string as unset: ensure you verify apiConfig.Region != nil && *apiConfig.Region != "" and if empty or nil set region = "default" before calling baseURLForRegion; adjust ChatWithMessages (and any similar callers) to normalize the region the same way so baseURLForRegion always receives a non-empty key and error messages remain consistent.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@conf/models/openrouter.json`:
- Around line 18-21: The config sets thinking.default_value: true for models
that don't emit reasoning tokens, causing drivers to inject reasoning fields and
fail the strict reasoning_content assertion in ChatWithMessages; change the
thinking.default_value to false for non-reasoning models (remove or set to false
in the openrouter model entry) so only models that actually emit reasoning
tokens (e.g., DeepSeek-R1 derivatives or Anthropic extended thinking) keep
default_value:true and avoid triggering the reasoning_content check.
- Around line 6-9: The OpenRouter URL suffix config is missing entries
referenced by the driver (o.URLSuffix.AsyncChat and o.URLSuffix.Rerank) used in
ChatStreamlyWithSender and Rerank in internal/entity/models/openrouter.go;
either remove those branches in the driver or add the missing keys to
conf/models/openrouter.json—specifically add an "async_chat" key and a "rerank"
key with the exact path segments the driver expects (match casing/underscores to
o.URLSuffix.AsyncChat and o.URLSuffix.Rerank) so URLs composed by the driver are
not malformed.
In `@internal/entity/models/lmstudio.go`:
- Around line 183-197: The code currently treats messageMap["reasoning_content"]
as required when chatModelConfig.Thinking is true and returns an error if
missing or non-string; change this to optional: in the block that checks
chatModelConfig != nil && chatModelConfig.Thinking != nil &&
*chatModelConfig.Thinking, only attempt to read and type-assert
messageMap["reasoning_content"] if the key exists, and do not return an error on
absence or wrong type—leave reasonContent nil (or empty) instead; if present and
a string, trim a leading newline as before; ensure ChatResponse.ReasonContent is
set to nil when no valid string was provided. Use the symbols messageMap,
"reasoning_content", reasonContent, chatModelConfig.Thinking, and ChatResponse
to locate and update the logic.
In `@internal/entity/models/nvidia.go`:
- Around line 168-182: The code currently errors if
messageMap["reasoning_content"] is missing or not a string when chatModelConfig
!= nil && chatModelConfig.Thinking is true; instead treat reasoning_content as
optional: check for the key and type without returning an error, handle nil
values, only strip the leading newline if the string is non-empty, and set
ChatResponse.ReasonContent to a nil pointer when absent; update the logic around
messageMap, reasoning_content, reasonContent and the ChatResponse construction
(referencing chatModelConfig, Thinking, messageMap, reasoning_content,
reasonContent, and ChatResponse) to implement this optional behavior.
In `@internal/entity/models/ollama.go`:
- Around line 182-196: The strict assertion on messageMap["reasoning_content"]
in the Ollama handling should not return an error when the field is absent or
not a string; update the logic in the block that checks chatModelConfig and
chatModelConfig.Thinking so that if reasoning_content is missing or cannot be
asserted to string you simply set reasonContent = "" (instead of returning
fmt.Errorf) and proceed, then keep the existing trim of a leading newline when
reasonContent is non-empty; update the code paths around messageMap,
reasoning_content, and the ChatResponse construction to remove the "invalid
content format" error return and treat missing/invalid field as empty.
In `@internal/entity/models/openrouter.go`:
- Around line 354-357: Replace the placeholder panics in OpenRouterModel methods
with proper error returns consistent with other drivers: in
OpenRouterModel.Encode, Balance, and CheckConnection return the zero value(s)
and fmt.Errorf("no such method") instead of panic("implement me") — e.g., Encode
should return nil, fmt.Errorf("no such method"); Balance should return 0.0,
fmt.Errorf("no such method") (or the correct zero types used elsewhere);
CheckConnection should return fmt.Errorf("no such method"); update imports to
include fmt if needed.
- Around line 359-427: The OpenRouterModel.Rerank implementation is calling
Siliconflow-specific types and endpoints (SiliconflowRerankRequest/Response and
o.URLSuffix.Rerank) which OpenRouter doesn't support; replace the body of Rerank
so it returns the same "no such method" error pattern used by other drivers
(e.g., fmt.Errorf("no such method")) and remove any Siliconflow types/URLs and
error strings referencing "SiliconFlow Rerank API"; if OpenRouter actually
supports a rerank endpoint, instead update the function to call the correct
OpenRouter endpoint and use provider-specific request/response structs and
o.URLSuffix entry for that endpoint.
- Around line 27-37: Swap the inverted HTTP transport pool values so the global
cap is larger than the per-host cap: in the OpenRouter client constructor (the
httpClient Transport in the openrouter.go initializer) and in NewInstance, set
MaxIdleConns to 100 and MaxIdleConnsPerHost to 10 (instead of the current
10/100) to match other drivers (vllm.go, ollama.go, lmstudio.go, xai.go) and
net/http semantics.
- Around line 171-180: The current logic inside the block referencing
chatModelConfig and chatModelConfig.Thinking/Thinking strictly asserts
messageMap["reasoning"] is present and a string and returns an error if not;
change it to treat reasoning as optional: look up messageMap["reasoning"] first
and fall back to messageMap["reasoning_content"], only validate type if a value
is present, and do not return an error when the keys are absent or not a
string—just leave reasonContent empty. Also keep the existing leading-newline
trim for reasonContent when set. Update the code around variables
chatModelConfig, Thinking, messageMap and reasonContent accordingly.
- Around line 449-451: In ListModels, avoid panicking by not unconditionally
dereferencing apiConfig.ApiKey when setting the Authorization header; instead,
only set req.Header.Set("Authorization", ...) if apiConfig != nil and
apiConfig.ApiKey != nil (and the pointed string is non-empty). Update the
Authorization header logic around the existing req.Header.Set calls in
ListModels so Content-Type is always set but Authorization is added
conditionally based on the presence of apiConfig and apiConfig.ApiKey.
- Around line 151-159: The code accesses choices[0] without checking for an
empty slice, causing a panic when OpenRouter returns an empty "choices" array;
update the handling around the result map parsing (the choices, ok :=
result["choices"].([]interface{}) block and the creation of firstChoice) to
check if len(choices) == 0 and return a descriptive error (e.g., "no choices in
response") before indexing, and ensure firstChoice is only assigned after that
guard to match other drivers' behavior.
- Around line 464-466: Fix the typo and remove the upstream URL from the
user-returned error in the HTTP response handling: change the error message
generated when resp.StatusCode != http.StatusOK (the return using resp, body and
url) to a concise message without the url and correct "API requestssss" to e.g.
"API request failed"; if the URL is useful for debugging, log it via common.Info
(or the project's logger) before returning the sanitized error so you keep
visibility without leaking the URL to callers.
- Around line 112-115: The code unconditionally injects reqBody["reasoning"] =
{"effort":"low"} for non-streaming requests; change it to only add the reasoning
object when chatModelConfig.Thinking is non-nil and true, and allow the
configured effort to be used instead of the hard-coded "low" (e.g., read the
effort value from chatModelConfig.Thinking.Effort or a similar field); mirror
the conditional logic used in ChatStreamlyWithSender (the ChatStreamlyWithSender
handling of chatModelConfig.Thinking) so users who opt out don’t get reasoning
forced on and so effort can be overridden.
- Around line 270-272: The code dereferences *apiConfig.ApiKey when setting the
Authorization header in ChatStreamlyWithSender (the
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey))
call) which can panic if apiConfig or apiConfig.ApiKey is nil; add the same
upfront nil checks used in ChatWithMessages (validate apiConfig != nil and
apiConfig.ApiKey != nil and return an error early) at the start of
ChatStreamlyWithSender (before computing region or using apiConfig) so the
header assignment is safe.
- Around line 476-480: The loop over result["data"] uses unchecked type
assertions and can panic; replace each single-return assertion with comma-ok
checks: verify result["data"] is a []interface{} before iterating, check each
model is a map[string]interface{} (modelMap), and check modelMap["id"] is a
string (modelName); on any type mismatch return a descriptive error instead of
panicking and only append valid modelName values to the models slice. Ensure
checks are applied in the code that constructs models from result (the variables
result, models, model, modelMap, and modelName in openrouter.go).
- Around line 202-205: The branch that derives modelType from modelName
(modelType := strings.Split(modelName, "_")[0]) and checks for "qwen" or "glm"
is dead for OpenRouter model IDs and uses o.URLSuffix.AsyncChat which isn't
configured; remove that conditional and always build the URL using
o.URLSuffix.Chat (i.e., replace the conditional URL assignment with a single
unconditional fmt.Sprintf using o.BaseURL[region] and o.URLSuffix.Chat) so
request URLs for OpenRouter are correctly formed; update any references in the
function that rely on modelType or AsyncChat accordingly (look for modelType,
modelName, o.URLSuffix.AsyncChat, o.URLSuffix.Chat in this function).
- Around line 248-258: The streaming handler ChatStreamlyWithSender currently
writes reqBody["thinking"] based on modelConfig.Thinking which OpenRouter
ignores; change this to set reqBody["reasoning"] with an "effort" field instead.
Specifically, in ChatStreamlyWithSender where modelConfig.Thinking is checked,
replace creation of reqBody["thinking"] with reqBody["reasoning"] =
map[string]interface{}{"effort": "<level>"} and map the boolean: when
*modelConfig.Thinking is true set effort to "low" (or the desired effort level),
when false set effort to "none" (or omit the field), so downstream code that
reads delta.reasoning will be activated.
In `@internal/entity/models/vllm.go`:
- Around line 199-208: The strict extraction of reasoning_content in the block
around chatModelConfig and Thinking causes failures when the field is missing or
non-string; update the logic in the function that reads messageMap to treat
messageMap["reasoning_content"] missing or not a string as an empty
reasonContent (do not return an error), only perform the leading-newline trim
when reasonContent != "" (i.e., after you have a non-empty string), and if you
must log an error use a clearer message referencing "reasoning_content" rather
than the generic "invalid content format"; keep the variable name reasonContent
and the check of chatModelConfig != nil && chatModelConfig.Thinking to scope
this change.
---
Outside diff comments:
In `@internal/entity/models/aliyun.go`:
- Around line 228-258: The code accesses chatModelConfig fields directly and
will panic when chatModelConfig is nil; wrap the entire block that sets
reqBody["stream"/"max_tokens"/.../"enable_thinking"] in a nil guard (e.g., if
chatModelConfig != nil { ... }) or otherwise early-return/skip this section when
chatModelConfig is nil so that references like chatModelConfig.Stream,
MaxTokens, Temperature, DoSample, TopP, Stop, and Thinking are only dereferenced
when chatModelConfig is non-nil.
In `@internal/entity/models/deepseek.go`:
- Around line 285-312: The streaming branch dereferences chatModelConfig.Effort
without a nil check (switch *chatModelConfig.Effort) causing a panic; change to
read a local effort string with a default (e.g., "high") like the non-streaming
ChatWithMessages path (set effort := "high" and if chatModelConfig.Effort != nil
then effort = *chatModelConfig.Effort), then switch on that local effort
variable instead of *chatModelConfig.Effort; also align behavior by removing the
default return error and handle unknown values consistently with
ChatWithMessages while still setting reqBody["reasoning_effort"] and
thinkingFlag for "high","default","max" cases.
In `@internal/entity/models/gitee.go`:
- Around line 244-278: The block that dereferences chatModelConfig (checking
Stream, MaxTokens, Temperature, DoSample, TopP, Stop, Thinking) should be
guarded by a nil check to avoid panics when callers pass nil; wrap the existing
sequence that sets entries on reqBody inside an if chatModelConfig != nil { ...
} so all references to chatModelConfig (in gitee.go where reqBody is populated)
only occur when chatModelConfig is non-nil, preserving the existing per-field
nil checks and the Thinking handling.
In `@internal/entity/models/lmstudio.go`:
- Around line 65-68: ChatWithMessages currently sets region using only
apiConfig.Region != nil and dereferences apiConfig without checking nil, which
allows an empty-string region to slip through; update the region determination
in ChatWithMessages to first ensure apiConfig != nil, then check
apiConfig.Region != nil && *apiConfig.Region != "" and only then set region =
*apiConfig.Region, otherwise keep region = "default" (mirror the guard used in
ChatStreamlyWithSender and ListModels) to avoid the unsupported protocol scheme
bug.
In `@internal/entity/models/moonshot.go`:
- Around line 231-265: The code reads fields from chatModelConfig without
checking for nil, which can panic; add a top-level nil guard (if chatModelConfig
!= nil) around the entire block that accesses chatModelConfig.Stream, MaxTokens,
Temperature, DoSample, TopP, Stop, and Thinking so none of those dereferences
occur when chatModelConfig is nil, preserving the existing behavior for each
field inside that guarded block.
In `@internal/entity/models/ollama.go`:
- Around line 64-67: The region handling in ChatWithMessages and ListModels is
still using the old apiConfig.Region != nil check and also dereferences
apiConfig without a nil guard, which allows an empty-string region or nil config
to produce empty BaseURL access or a panic; update both ChatWithMessages and
ListModels to mirror ChatStreamlyWithSender by first checking apiConfig != nil,
then treating an empty or nil Region as "default" (e.g., set region :=
"default"; if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region
!= "" { region = *apiConfig.Region }), and then use that region when accessing
o.BaseURL[region].
In `@internal/entity/models/openai.go`:
- Around line 102-105: ChatWithMessages and ListModels still set region directly
from apiConfig.Region when non-nil, allowing empty strings to be passed to
baseURLForRegion; update both methods to mirror ChatStreamlyWithSender by
assigning region only when apiConfig.Region is non-nil AND the pointed string is
non-empty (e.g., check apiConfig.Region != nil && *apiConfig.Region != "" before
setting region = *apiConfig.Region) so baseURLForRegion never receives an empty
region.
In `@internal/entity/models/volcengine.go`:
- Around line 70-72: In the Chat method, the region nil-check is inconsistent
with ChatWithMessages, ChatStreamlyWithSender, and CheckConnection—update the
guard that sets the local region so it verifies both that apiConfig.Region is
non-nil and that *apiConfig.Region is not an empty string (e.g., replace the
current nil-only check with a combined non-nil && non-empty check) so the region
variable is only set when apiConfig.Region contains a non-empty value; refer to
the Chat method and the apiConfig.Region and region variables when making this
change to match the other methods' behavior.
---
Nitpick comments:
In `@internal/entity/models/aliyun.go`:
- Around line 382-384: ListModels still treats a nil Region pointer as the only
"unset" case, so an empty-string region from the UI slips through; update the
guard in ListModels (the block that currently reads if apiConfig.Region != nil {
region = *apiConfig.Region }) to treat empty or whitespace-only strings as
unset—e.g., check apiConfig.Region != nil &&
strings.TrimSpace(*apiConfig.Region) != "" before assigning to region—so
CheckConnection and other callers won't proceed with an empty region.
In `@internal/entity/models/deepseek.go`:
- Around line 434-437: In ListModels update the region guard to treat both nil
and empty-string the same as the other path: if apiConfig.Region is nil OR
*apiConfig.Region == "" set region = "default" so CheckConnection (which calls
ListModels) no longer allows an empty-string region to be used as a map key;
locate the region variable and the ListModels function in
internal/entity/models/deepseek.go and apply the same empty-string check you
used elsewhere where apiConfig.Region is validated.
In `@internal/entity/models/gitee.go`:
- Around line 410-414: The three methods ListModels, Balance, and
CheckConnection currently only check for apiConfig.Region != nil and can still
use an empty string as the region (causing unsupported protocol scheme ""), so
update each method (ListModels, Balance, CheckConnection on type GiteeModel) to
validate apiConfig.Region by checking both that it is non-nil and that
*apiConfig.Region != "" before assigning it to region; leave the default region
value when the pointer is nil or the string is empty and ensure all uses of
region in those functions rely on the validated value.
In `@internal/entity/models/moonshot.go`:
- Around line 366-369: ListModels and Balance still accept apiConfig.Region when
it's non-nil but empty, causing an empty base URL in CheckConnection; update
both functions (ListModels and Balance) to treat nil or empty-string regions the
same as omitted by initializing region := "default" and only override it when
apiConfig.Region != nil && *apiConfig.Region != "" so the region fallback is
applied and no empty base URL is produced.
In `@internal/entity/models/siliconflow.go`:
- Around line 476-478: ListModels (and callers like CheckConnection) can be
invoked with apiConfig.Region unset causing an empty-string region; ensure
ListModels never runs with an empty region by validating/normalizing
apiConfig.Region before calling or inside ListModels: in the CheckConnection
path and any caller that uses the local variable region (the code that reads
apiConfig.Region into region), check for nil or empty string and either set a
safe default or return a clear error, and add the same guard at the start of
ListModels to validate the region parameter so ListModels itself refuses to
operate with an empty region; update the code paths referencing apiConfig.Region
and the local region variable to use this normalized value.
In `@internal/entity/models/xai.go`:
- Around line 100-110: The region check in ChatWithMessages is looser than other
methods; update its guard to match ChatStreamlyWithSender and ListModels by
treating an empty-region string as unset: ensure you verify apiConfig.Region !=
nil && *apiConfig.Region != "" and if empty or nil set region = "default" before
calling baseURLForRegion; adjust ChatWithMessages (and any similar callers) to
normalize the region the same way so baseURLForRegion always receives a
non-empty key and error messages remain consistent.
In `@internal/entity/models/zhipu-ai.go`:
- Around line 368-370: The region guard in Encode and Rerank currently only
checks for nil so an empty-string region ends up being used as a map key; update
both guards (where apiConfig.Region and region are handled in Encode and Rerank)
to require a non-empty string as well (i.e., check apiConfig.Region != nil AND
*apiConfig.Region != "" before assigning region) so empty-string regions do not
override the default base URL lookup.
🪄 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: c5506636-8dc8-43c9-b2f2-78eac6b53c27
📒 Files selected for processing (17)
conf/models/openrouter.jsoninternal/entity/models/aliyun.gointernal/entity/models/deepseek.gointernal/entity/models/factory.gointernal/entity/models/gitee.gointernal/entity/models/lmstudio.gointernal/entity/models/minimax.gointernal/entity/models/moonshot.gointernal/entity/models/nvidia.gointernal/entity/models/ollama.gointernal/entity/models/openai.gointernal/entity/models/openrouter.gointernal/entity/models/siliconflow.gointernal/entity/models/vllm.gointernal/entity/models/volcengine.gointernal/entity/models/xai.gointernal/entity/models/zhipu-ai.go
💤 Files with no reviewable changes (1)
- internal/entity/models/minimax.go
| "url_suffix": { | ||
| "chat": "chat/completions", | ||
| "models": "models" | ||
| }, |
There was a problem hiding this comment.
Missing async_chat and rerank URL suffixes referenced by the driver.
internal/entity/models/openrouter.go references o.URLSuffix.AsyncChat (for qwen/glm routing in ChatStreamlyWithSender, Line 204) and o.URLSuffix.Rerank (in Rerank, Line 389). Neither is declared here, so those code paths will produce malformed URLs (e.g., https://openrouter.ai/api/v1/). See the corresponding comments on openrouter.go — most of those branches should be removed, but if any are kept, the suffixes must be added here.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@conf/models/openrouter.json` around lines 6 - 9, The OpenRouter URL suffix
config is missing entries referenced by the driver (o.URLSuffix.AsyncChat and
o.URLSuffix.Rerank) used in ChatStreamlyWithSender and Rerank in
internal/entity/models/openrouter.go; either remove those branches in the driver
or add the missing keys to conf/models/openrouter.json—specifically add an
"async_chat" key and a "rerank" key with the exact path segments the driver
expects (match casing/underscores to o.URLSuffix.AsyncChat and
o.URLSuffix.Rerank) so URLs composed by the driver are not malformed.
| "thinking": { | ||
| "default_value": true, | ||
| "clear_thinking": true | ||
| } |
There was a problem hiding this comment.
thinking.default_value: true is not appropriate for non-reasoning models.
Setting default_value: true forces the Thinking flag on for every chat call. For models that don't expose reasoning tokens (e.g., the Gemma family), this means the driver will inject reasoning/thinking request fields and then fail on the strict reasoning_content assertion in ChatWithMessages. Only enable default_value: true for models that actually emit reasoning tokens (DeepSeek-R1 derivatives, Anthropic extended thinking, etc.).
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@conf/models/openrouter.json` around lines 18 - 21, The config sets
thinking.default_value: true for models that don't emit reasoning tokens,
causing drivers to inject reasoning fields and fail the strict reasoning_content
assertion in ChatWithMessages; change the thinking.default_value to false for
non-reasoning models (remove or set to false in the openrouter model entry) so
only models that actually emit reasoning tokens (e.g., DeepSeek-R1 derivatives
or Anthropic extended thinking) keep default_value:true and avoid triggering the
reasoning_content check.
| var reasonContent string | ||
| if chatModelConfig != nil && chatModelConfig.Thinking != nil && *chatModelConfig.Thinking { | ||
| reasonContent, ok = messageMap["reasoning_content"].(string) | ||
| if !ok { | ||
| return nil, fmt.Errorf("invalid content format") | ||
| } | ||
| if reasonContent != "" && reasonContent[0] == '\n' { | ||
| reasonContent = reasonContent[1:] | ||
| } | ||
| } | ||
|
|
||
| chatResponse := &ChatResponse{ | ||
| Answer: answer, | ||
| ReasonContent: thinking, | ||
| Answer: &content, | ||
| ReasonContent: &reasonContent, | ||
| } |
There was a problem hiding this comment.
Strict reasoning_content assertion can break valid responses.
Same concern as vllm/ollama drivers: a Thinking-enabled call will fail with "invalid content format" whenever the upstream omits reasoning_content (legitimate for short answers or models that skip the reasoning trace). Make the field optional.
🛡️ Suggested fix
var reasonContent string
if chatModelConfig != nil && chatModelConfig.Thinking != nil && *chatModelConfig.Thinking {
- reasonContent, ok = messageMap["reasoning_content"].(string)
- if !ok {
- return nil, fmt.Errorf("invalid content format")
- }
- if reasonContent != "" && reasonContent[0] == '\n' {
+ if rc, ok := messageMap["reasoning_content"].(string); ok {
+ reasonContent = rc
+ }
+ if len(reasonContent) > 0 && reasonContent[0] == '\n' {
reasonContent = reasonContent[1:]
}
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| var reasonContent string | |
| if chatModelConfig != nil && chatModelConfig.Thinking != nil && *chatModelConfig.Thinking { | |
| reasonContent, ok = messageMap["reasoning_content"].(string) | |
| if !ok { | |
| return nil, fmt.Errorf("invalid content format") | |
| } | |
| if reasonContent != "" && reasonContent[0] == '\n' { | |
| reasonContent = reasonContent[1:] | |
| } | |
| } | |
| chatResponse := &ChatResponse{ | |
| Answer: answer, | |
| ReasonContent: thinking, | |
| Answer: &content, | |
| ReasonContent: &reasonContent, | |
| } | |
| var reasonContent string | |
| if chatModelConfig != nil && chatModelConfig.Thinking != nil && *chatModelConfig.Thinking { | |
| if rc, ok := messageMap["reasoning_content"].(string); ok { | |
| reasonContent = rc | |
| } | |
| if len(reasonContent) > 0 && reasonContent[0] == '\n' { | |
| reasonContent = reasonContent[1:] | |
| } | |
| } | |
| chatResponse := &ChatResponse{ | |
| Answer: &content, | |
| ReasonContent: &reasonContent, | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/entity/models/lmstudio.go` around lines 183 - 197, The code
currently treats messageMap["reasoning_content"] as required when
chatModelConfig.Thinking is true and returns an error if missing or non-string;
change this to optional: in the block that checks chatModelConfig != nil &&
chatModelConfig.Thinking != nil && *chatModelConfig.Thinking, only attempt to
read and type-assert messageMap["reasoning_content"] if the key exists, and do
not return an error on absence or wrong type—leave reasonContent nil (or empty)
instead; if present and a string, trim a leading newline as before; ensure
ChatResponse.ReasonContent is set to nil when no valid string was provided. Use
the symbols messageMap, "reasoning_content", reasonContent,
chatModelConfig.Thinking, and ChatResponse to locate and update the logic.
| var reasonContent string | ||
| if chatModelConfig != nil && chatModelConfig.Thinking != nil && *chatModelConfig.Thinking { | ||
| reasonContent, ok = messageMap["reasoning_content"].(string) | ||
| if !ok { | ||
| return nil, fmt.Errorf("invalid content format") | ||
| } | ||
| if reasonContent != "" && reasonContent[0] == '\n' { | ||
| reasonContent = reasonContent[1:] | ||
| } | ||
| } | ||
| thinking, answer := GetThinkingAndAnswer(modelClass, &content) | ||
|
|
||
| chatResponse := &ChatResponse{ | ||
| Answer: answer, | ||
| ReasonContent: thinking, | ||
| Answer: &content, | ||
| ReasonContent: &reasonContent, | ||
| } |
There was a problem hiding this comment.
Strict reasoning_content assertion can break valid responses.
Same concern as the other drivers in this PR: when Thinking is enabled but the model omits reasoning_content (or returns null), the call fails with "invalid content format" even though content was valid. Treat the field as optional.
🛡️ Suggested fix
var reasonContent string
if chatModelConfig != nil && chatModelConfig.Thinking != nil && *chatModelConfig.Thinking {
- reasonContent, ok = messageMap["reasoning_content"].(string)
- if !ok {
- return nil, fmt.Errorf("invalid content format")
- }
- if reasonContent != "" && reasonContent[0] == '\n' {
+ if rc, ok := messageMap["reasoning_content"].(string); ok {
+ reasonContent = rc
+ }
+ if len(reasonContent) > 0 && reasonContent[0] == '\n' {
reasonContent = reasonContent[1:]
}
}🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/entity/models/nvidia.go` around lines 168 - 182, The code currently
errors if messageMap["reasoning_content"] is missing or not a string when
chatModelConfig != nil && chatModelConfig.Thinking is true; instead treat
reasoning_content as optional: check for the key and type without returning an
error, handle nil values, only strip the leading newline if the string is
non-empty, and set ChatResponse.ReasonContent to a nil pointer when absent;
update the logic around messageMap, reasoning_content, reasonContent and the
ChatResponse construction (referencing chatModelConfig, Thinking, messageMap,
reasoning_content, reasonContent, and ChatResponse) to implement this optional
behavior.
| var reasonContent string | ||
| if chatModelConfig != nil && chatModelConfig.Thinking != nil && *chatModelConfig.Thinking { | ||
| reasonContent, ok = messageMap["reasoning_content"].(string) | ||
| if !ok { | ||
| return nil, fmt.Errorf("invalid content format") | ||
| } | ||
| if reasonContent != "" && reasonContent[0] == '\n' { | ||
| reasonContent = reasonContent[1:] | ||
| } | ||
| } | ||
|
|
||
| chatResponse := &ChatResponse{ | ||
| Answer: answer, | ||
| ReasonContent: thinking, | ||
| Answer: &content, | ||
| ReasonContent: &reasonContent, | ||
| } |
There was a problem hiding this comment.
Strict reasoning_content assertion can fail on valid upstream responses.
Same issue as in vllm.go: when Thinking is enabled but the model omits reasoning_content (which is allowed — Ollama may return only content for short replies), the type assertion fails and the entire response is rejected. Treat a missing field as empty rather than erroring out, and the misleading "invalid content format" message should also be removed.
🛡️ Suggested fix
var reasonContent string
if chatModelConfig != nil && chatModelConfig.Thinking != nil && *chatModelConfig.Thinking {
- reasonContent, ok = messageMap["reasoning_content"].(string)
- if !ok {
- return nil, fmt.Errorf("invalid content format")
- }
- if reasonContent != "" && reasonContent[0] == '\n' {
+ if rc, ok := messageMap["reasoning_content"].(string); ok {
+ reasonContent = rc
+ }
+ if len(reasonContent) > 0 && reasonContent[0] == '\n' {
reasonContent = reasonContent[1:]
}
}🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/entity/models/ollama.go` around lines 182 - 196, The strict
assertion on messageMap["reasoning_content"] in the Ollama handling should not
return an error when the field is absent or not a string; update the logic in
the block that checks chatModelConfig and chatModelConfig.Thinking so that if
reasoning_content is missing or cannot be asserted to string you simply set
reasonContent = "" (instead of returning fmt.Errorf) and proceed, then keep the
existing trim of a leading newline when reasonContent is non-empty; update the
code paths around messageMap, reasoning_content, and the ChatResponse
construction to remove the "invalid content format" error return and treat
missing/invalid field as empty.
| func (o *OpenRouterModel) Rerank(modelName *string, query string, texts []string, apiConfig *APIConfig) ([]float64, error) { | ||
| if len(texts) == 0 { | ||
| return []float64{}, nil | ||
| } | ||
|
|
||
| var region = "default" | ||
| if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" { | ||
| region = *apiConfig.Region | ||
| } | ||
|
|
||
| apiKey := "" | ||
| if apiConfig != nil && apiConfig.ApiKey != nil { | ||
| apiKey = *apiConfig.ApiKey | ||
| } | ||
|
|
||
| reqBody := SiliconflowRerankRequest{ | ||
| Model: *modelName, | ||
| Query: query, | ||
| Documents: texts, | ||
| TopN: len(texts), | ||
| ReturnDocuments: false, | ||
| MaxChunksPerDoc: 1024, | ||
| OverlapTokens: 80, | ||
| } | ||
|
|
||
| jsonData, err := json.Marshal(reqBody) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to marshal request: %w", err) | ||
| } | ||
|
|
||
| url := fmt.Sprintf("%s/%s", strings.TrimSuffix(o.BaseURL[region], "/"), o.URLSuffix.Rerank) | ||
|
|
||
| req, err := http.NewRequest("POST", url, strings.NewReader(string(jsonData))) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to create request: %w", err) | ||
| } | ||
|
|
||
| req.Header.Set("Content-Type", "application/json") | ||
| if apiKey != "" { | ||
| req.Header.Set("Authorization", "Bearer "+apiKey) | ||
| } | ||
|
|
||
| resp, err := o.httpClient.Do(req) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to send request: %w", err) | ||
| } | ||
| defer resp.Body.Close() | ||
|
|
||
| if resp.StatusCode != http.StatusOK { | ||
| body, _ := io.ReadAll(resp.Body) | ||
| return nil, fmt.Errorf("SiliconFlow Rerank API error: %s, body: %s", resp.Status, string(body)) | ||
| } | ||
|
|
||
| body, _ := io.ReadAll(resp.Body) | ||
|
|
||
| var rerankResp SiliconflowRerankResponse | ||
| if err := json.Unmarshal(body, &rerankResp); err != nil { | ||
| return nil, fmt.Errorf("failed to decode response: %w", err) | ||
| } | ||
|
|
||
| scores := make([]float64, len(texts)) | ||
| for _, result := range rerankResp.Results { | ||
| if result.Index >= 0 && result.Index < len(texts) { | ||
| scores[result.Index] = result.RelevanceScore | ||
| } | ||
| } | ||
|
|
||
| return scores, nil | ||
| } |
There was a problem hiding this comment.
Rerank calls a Siliconflow endpoint and is unlikely to work for OpenRouter.
This implementation marshals a SiliconflowRerankRequest, expects a SiliconflowRerankResponse, and emits an error string referencing "SiliconFlow Rerank API". OpenRouter does not currently expose a rerank API — the public docs only document chat completions, completions, and /models. Additionally, o.URLSuffix.Rerank is not configured in conf/models/openrouter.json, so this will POST to https://openrouter.ai/api/v1/ and fail.
If rerank is genuinely not supported, replace the body with the same fmt.Errorf("no such method") pattern used by the other drivers. Otherwise, point this at the actual provider/endpoint and remove the Siliconflow types from the error message.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/entity/models/openrouter.go` around lines 359 - 427, The
OpenRouterModel.Rerank implementation is calling Siliconflow-specific types and
endpoints (SiliconflowRerankRequest/Response and o.URLSuffix.Rerank) which
OpenRouter doesn't support; replace the body of Rerank so it returns the same
"no such method" error pattern used by other drivers (e.g., fmt.Errorf("no such
method")) and remove any Siliconflow types/URLs and error strings referencing
"SiliconFlow Rerank API"; if OpenRouter actually supports a rerank endpoint,
instead update the function to call the correct OpenRouter endpoint and use
provider-specific request/response structs and o.URLSuffix entry for that
endpoint.
|
|
||
| req.Header.Set("Content-Type", "application/json") | ||
| req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) |
There was a problem hiding this comment.
Nil deref of apiConfig.ApiKey in ListModels.
ListModels does an apiConfig != nil check on Line 431 only for region computation, then unconditionally dereferences *apiConfig.ApiKey here. A nil apiConfig (or a config with a nil ApiKey) will panic. Note that OpenRouter's /api/v1/models endpoint is in fact callable without auth, so the cleaner fix is to make the header conditional rather than hard-required.
🛡️ Suggested fix
req.Header.Set("Content-Type", "application/json")
- req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey))
+ if apiConfig != nil && apiConfig.ApiKey != nil && *apiConfig.ApiKey != "" {
+ req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey))
+ }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| req.Header.Set("Content-Type", "application/json") | |
| req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) | |
| req.Header.Set("Content-Type", "application/json") | |
| if apiConfig != nil && apiConfig.ApiKey != nil && *apiConfig.ApiKey != "" { | |
| req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/entity/models/openrouter.go` around lines 449 - 451, In ListModels,
avoid panicking by not unconditionally dereferencing apiConfig.ApiKey when
setting the Authorization header; instead, only set
req.Header.Set("Authorization", ...) if apiConfig != nil and apiConfig.ApiKey !=
nil (and the pointed string is non-empty). Update the Authorization header logic
around the existing req.Header.Set calls in ListModels so Content-Type is always
set but Authorization is added conditionally based on the presence of apiConfig
and apiConfig.ApiKey.
| if resp.StatusCode != http.StatusOK { | ||
| return nil, fmt.Errorf("API requestssss failed with status %d: %s : %s", resp.StatusCode, string(body), url) | ||
| } |
There was a problem hiding this comment.
Typo and URL leakage in error message.
"API requestssss failed" is a typo. Including the upstream URL in user-visible errors also unnecessarily widens the surface area for log/UI exposure of internal config. Drop the URL or, if it's useful for debugging, log it via common.Info instead of returning it.
♻️ Suggested fix
- return nil, fmt.Errorf("API requestssss failed with status %d: %s : %s", resp.StatusCode, string(body), url)
+ return nil, fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if resp.StatusCode != http.StatusOK { | |
| return nil, fmt.Errorf("API requestssss failed with status %d: %s : %s", resp.StatusCode, string(body), url) | |
| } | |
| if resp.StatusCode != http.StatusOK { | |
| return nil, fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body)) | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/entity/models/openrouter.go` around lines 464 - 466, Fix the typo
and remove the upstream URL from the user-returned error in the HTTP response
handling: change the error message generated when resp.StatusCode !=
http.StatusOK (the return using resp, body and url) to a concise message without
the url and correct "API requestssss" to e.g. "API request failed"; if the URL
is useful for debugging, log it via common.Info (or the project's logger) before
returning the sanitized error so you keep visibility without leaking the URL to
callers.
| for _, model := range result["data"].([]interface{}) { | ||
| modelMap := model.(map[string]interface{}) | ||
| modelName := modelMap["id"].(string) | ||
| models = append(models, modelName) | ||
| } |
There was a problem hiding this comment.
Unchecked type assertions on the models response can panic.
result["data"].([]interface{}), model.(map[string]interface{}), and modelMap["id"].(string) all use the single-return form of type assertion, so any unexpected payload shape (e.g., OpenRouter returning {"error": {...}} with HTTP 200, or a model entry without an id) will panic instead of returning a clean error. Use the comma-ok form like other drivers do (e.g., xai.go Lines 455-471).
🛡️ Suggested fix
- models := make([]string, 0)
- for _, model := range result["data"].([]interface{}) {
- modelMap := model.(map[string]interface{})
- modelName := modelMap["id"].(string)
- models = append(models, modelName)
- }
+ data, ok := result["data"].([]interface{})
+ if !ok {
+ return nil, fmt.Errorf("invalid models list format")
+ }
+ models := make([]string, 0, len(data))
+ for _, model := range data {
+ modelMap, ok := model.(map[string]interface{})
+ if !ok {
+ continue
+ }
+ id, ok := modelMap["id"].(string)
+ if !ok {
+ continue
+ }
+ models = append(models, id)
+ }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/entity/models/openrouter.go` around lines 476 - 480, The loop over
result["data"] uses unchecked type assertions and can panic; replace each
single-return assertion with comma-ok checks: verify result["data"] is a
[]interface{} before iterating, check each model is a map[string]interface{}
(modelMap), and check modelMap["id"] is a string (modelName); on any type
mismatch return a descriptive error instead of panicking and only append valid
modelName values to the models slice. Ensure checks are applied in the code that
constructs models from result (the variables result, models, model, modelMap,
and modelName in openrouter.go).
| var reasonContent string | ||
| if chatModelConfig != nil && chatModelConfig.Thinking != nil && *chatModelConfig.Thinking { | ||
| reasonContent, ok = messageMap["reasoning_content"].(string) | ||
| if !ok { | ||
| return nil, fmt.Errorf("invalid content format") | ||
| } | ||
| if reasonContent != "" && reasonContent[0] == '\n' { | ||
| reasonContent = reasonContent[1:] | ||
| } | ||
| } |
There was a problem hiding this comment.
Strict reasoning_content extraction can break valid responses.
When chatModelConfig.Thinking is enabled, the code returns an error if reasoning_content is absent or non-string in the response. Many upstream models honor thinking: enabled but still omit the field for short answers, or return null. In that case the entire chat call fails even though content is valid. Also, the error message "invalid content format" is misleading — it's reasoning, not content.
Treat a missing/non-string reasoning_content as an empty string instead of an error, and only emit the leading-newline trim on a non-empty value.
🛡️ Suggested fix
var reasonContent string
if chatModelConfig != nil && chatModelConfig.Thinking != nil && *chatModelConfig.Thinking {
- reasonContent, ok = messageMap["reasoning_content"].(string)
- if !ok {
- return nil, fmt.Errorf("invalid content format")
- }
- if reasonContent != "" && reasonContent[0] == '\n' {
+ if rc, ok := messageMap["reasoning_content"].(string); ok {
+ reasonContent = rc
+ }
+ if len(reasonContent) > 0 && reasonContent[0] == '\n' {
reasonContent = reasonContent[1:]
}
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| var reasonContent string | |
| if chatModelConfig != nil && chatModelConfig.Thinking != nil && *chatModelConfig.Thinking { | |
| reasonContent, ok = messageMap["reasoning_content"].(string) | |
| if !ok { | |
| return nil, fmt.Errorf("invalid content format") | |
| } | |
| if reasonContent != "" && reasonContent[0] == '\n' { | |
| reasonContent = reasonContent[1:] | |
| } | |
| } | |
| var reasonContent string | |
| if chatModelConfig != nil && chatModelConfig.Thinking != nil && *chatModelConfig.Thinking { | |
| if rc, ok := messageMap["reasoning_content"].(string); ok { | |
| reasonContent = rc | |
| } | |
| if len(reasonContent) > 0 && reasonContent[0] == '\n' { | |
| reasonContent = reasonContent[1:] | |
| } | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/entity/models/vllm.go` around lines 199 - 208, The strict extraction
of reasoning_content in the block around chatModelConfig and Thinking causes
failures when the field is missing or non-string; update the logic in the
function that reads messageMap to treat messageMap["reasoning_content"] missing
or not a string as an empty reasonContent (do not return an error), only perform
the leading-newline trim when reasonContent != "" (i.e., after you have a
non-empty string), and if you must log an error use a clearer message
referencing "reasoning_content" rather than the generic "invalid content
format"; keep the variable name reasonContent and the check of chatModelConfig
!= nil && chatModelConfig.Thinking to scope this change.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14652 +/- ##
==========================================
- Coverage 95.59% 94.16% -1.43%
==========================================
Files 10 10
Lines 703 703
Branches 112 112
==========================================
- Hits 672 662 -10
- Misses 21 25 +4
- Partials 10 16 +6 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
### What problem does this PR solve? 1. **Implement `OpenRouter` Provider:** Fully support OpenRouter AI models (e.g., `gemma`, `minimax`). Includes robust handling of Server-Sent Events (SSE) streams, error event interception, and proper parsing of both `reasoning_content` and standard `content`. 2. **Fix BaseURL Resolution Bug:** Fixed a critical edge case in region configuration parsing. Added a strict empty string check (`*apiConfig.Region != ""`) alongside the `nil` check. This ensures that if the UI passes an empty string, the system correctly falls back to the `"default"` region, preventing `unsupported protocol scheme ""` errors during HTTP requests. ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue) - [x] New Feature (non-breaking change which adds functionality)
### What problem does this PR solve? Add a Go driver for StepFun (阶跃星辰), one of the unchecked providers on the umbrella tracking issue #14736. Until this PR, a tenant who configured `stepfun` as a model provider in the Go layer fell through to the default branch of `internal/entity/models/factory.go` and got the dummy driver. Chat, list models, and check connection all returned `"not implemented"` instead of reaching the StepFun API. The Python side has had StepFun registered in `rag/llm/__init__.py` as a `SupportedLiteLLMProvider` with base URL `https://api.stepfun.com/v1`, plus `StepFunCV` for vision and `StepFunSeq2txt` for ASR, but no Go path. StepFun's chat API is OpenAI-compatible, so the implementation pattern is the same as the merged Moonshot driver (#14433) and OpenAI driver (#14605). ### What this PR includes - New file `internal/entity/models/stepfun.go` with a `StepFunModel` that implements the `ModelDriver` interface. - `factory.go`: route the `"stepfun"` provider name to `NewStepFunModel`. - New `conf/models/stepfun.json` with the public StepFun chat models (step-2-16k, step-1 family in 8k/32k/128k/256k context lengths, step-1-flash, and the step-1v / step-1o vision models) and `url_suffix` entries for `chat` and `models`. ### How the driver works - StepFun exposes the OpenAI-compatible API at `https://api.stepfun.com/v1`. - `ChatWithMessages` and `ChatStreamlyWithSender` post to `/chat/completions` in the same shape as the merged moonshot, openrouter, and openai drivers. - `ListModels` and `CheckConnection` call `/models` to list available ids and confirm the API key works. - `Embed` is left as `"not implemented"`. StepFun has not advertised a public embeddings endpoint in the API reference linked from the umbrella issue (`https://platform.stepfun.com/docs/en/api-reference/chat/chat-completion-create` is the chat endpoint), so any real implementation belongs in a separate follow-up only after the endpoint is verified. - `Rerank` and `Balance` return `"no such method"` because StepFun does not expose either. ### Type of change - [x] New Feature (non-breaking change which adds functionality) ### How was this tested? - `go build ./internal/entity/models/...` returns exit 0 with no errors on go 1.25 (the `go.mod` minimum). - Method set of `StepFunModel` matches the `ModelDriver` interface: `NewInstance`, `Name`, `ChatWithMessages`, `ChatStreamlyWithSender`, `Embed`, `Rerank`, `ListModels`, `Balance`, `CheckConnection`. - Pattern parity with the merged moonshot (#14433), openai (#14605), openrouter (#14652), and xai (#14550) drivers. Closes #14814 Tracking: #14736
### What problem does this PR solve? 1. **Implement `OpenRouter` Provider:** Fully support OpenRouter AI models (e.g., `gemma`, `minimax`). Includes robust handling of Server-Sent Events (SSE) streams, error event interception, and proper parsing of both `reasoning_content` and standard `content`. 2. **Fix BaseURL Resolution Bug:** Fixed a critical edge case in region configuration parsing. Added a strict empty string check (`*apiConfig.Region != ""`) alongside the `nil` check. This ensures that if the UI passes an empty string, the system correctly falls back to the `"default"` region, preventing `unsupported protocol scheme ""` errors during HTTP requests. ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue) - [x] New Feature (non-breaking change which adds functionality)
### What problem does this PR solve? Add a Go driver for StepFun (阶跃星辰), one of the unchecked providers on the umbrella tracking issue infiniflow#14736. Until this PR, a tenant who configured `stepfun` as a model provider in the Go layer fell through to the default branch of `internal/entity/models/factory.go` and got the dummy driver. Chat, list models, and check connection all returned `"not implemented"` instead of reaching the StepFun API. The Python side has had StepFun registered in `rag/llm/__init__.py` as a `SupportedLiteLLMProvider` with base URL `https://api.stepfun.com/v1`, plus `StepFunCV` for vision and `StepFunSeq2txt` for ASR, but no Go path. StepFun's chat API is OpenAI-compatible, so the implementation pattern is the same as the merged Moonshot driver (infiniflow#14433) and OpenAI driver (infiniflow#14605). ### What this PR includes - New file `internal/entity/models/stepfun.go` with a `StepFunModel` that implements the `ModelDriver` interface. - `factory.go`: route the `"stepfun"` provider name to `NewStepFunModel`. - New `conf/models/stepfun.json` with the public StepFun chat models (step-2-16k, step-1 family in 8k/32k/128k/256k context lengths, step-1-flash, and the step-1v / step-1o vision models) and `url_suffix` entries for `chat` and `models`. ### How the driver works - StepFun exposes the OpenAI-compatible API at `https://api.stepfun.com/v1`. - `ChatWithMessages` and `ChatStreamlyWithSender` post to `/chat/completions` in the same shape as the merged moonshot, openrouter, and openai drivers. - `ListModels` and `CheckConnection` call `/models` to list available ids and confirm the API key works. - `Embed` is left as `"not implemented"`. StepFun has not advertised a public embeddings endpoint in the API reference linked from the umbrella issue (`https://platform.stepfun.com/docs/en/api-reference/chat/chat-completion-create` is the chat endpoint), so any real implementation belongs in a separate follow-up only after the endpoint is verified. - `Rerank` and `Balance` return `"no such method"` because StepFun does not expose either. ### Type of change - [x] New Feature (non-breaking change which adds functionality) ### How was this tested? - `go build ./internal/entity/models/...` returns exit 0 with no errors on go 1.25 (the `go.mod` minimum). - Method set of `StepFunModel` matches the `ModelDriver` interface: `NewInstance`, `Name`, `ChatWithMessages`, `ChatStreamlyWithSender`, `Embed`, `Rerank`, `ListModels`, `Balance`, `CheckConnection`. - Pattern parity with the merged moonshot (infiniflow#14433), openai (infiniflow#14605), openrouter (infiniflow#14652), and xai (infiniflow#14550) drivers. Closes infiniflow#14814 Tracking: infiniflow#14736
What problem does this PR solve?
OpenRouterProvider: Fully support OpenRouter AI models (e.g.,gemma,minimax). Includes robust handling of Server-Sent Events (SSE) streams, error event interception, and proper parsing of bothreasoning_contentand standardcontent.*apiConfig.Region != "") alongside thenilcheck. This ensures that if the UI passes an empty string, the system correctly falls back to the"default"region, preventingunsupported protocol scheme ""errors during HTTP requests.Type of change