Repository navigation
Go: add gitee and siliconflow as model provider - #14336
Conversation
Signed-off-by: Jin Hai <[email protected]>
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds per-provider/model "series" metadata, new Gitee and Siliconflow model drivers (chat, streaming, list, balance), DeepSeek unmarshalling updates, a thinking/answer parsing helper, and routes model series through chat request handling and CLI/handler routing changes. Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant API as Service/API
participant Driver as GiteeModel
participant ProviderAPI as Gitee API
participant Sender
Client->>API: POST /instances/:inst/models { model_name, message, stream, thinking }
API->>Driver: ChatStreamlyWithSender(modelName, message, apiConfig, chatConfig, sender)
Driver->>ProviderAPI: POST /chat/completions (stream=true)
ProviderAPI-->>Driver: SSE stream (data: JSON chunks / [DONE])
alt chunk contains thinking
Driver->>Sender: send(thinking fragment)
else chunk contains answer
Driver->>Sender: send(answer fragment)
end
Driver->>Sender: send("[DONE]")
Sender-->>Client: forwards streamed fragments
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 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 |
Signed-off-by: Jin Hai <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 7
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/service/model_service.go (1)
781-797:⚠️ Potential issue | 🟠 MajorPropagate
ModelSeriesfor streaming chats too.The streaming path still discards the resolved model, so series-specific parsing/config works for
ChatToModelbut notChatStreamlyWithSender.Proposed fix
- _, err = dao.GetModelProviderManager().GetModelByName(providerName, modelName) + var model *entity.Model + model, err = dao.GetModelProviderManager().GetModelByName(providerName, modelName) if err != nil { return common.CodeNotFound } + + if modelConfig == nil { + modelConfig = &modelModule.ChatConfig{} + } + modelConfig.ModelSeries = model.Series var extra map[string]string err = json.Unmarshal([]byte(instance.Extra), &extra) if err != nil { return common.CodeServerError🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/service/model_service.go` around lines 781 - 797, The resolved model's ModelSeries isn't being propagated into the streaming path: change the call to GetModelByName to capture the returned model info (e.g., modelInfo, err := dao.GetModelProviderManager().GetModelByName(providerName, modelName)), extract its ModelSeries (modelInfo.ModelSeries) and set the same field used by the non-streaming path (for example assign it into modelConfig.ModelSeries or apiConfig.ModelSeries) before calling ChatStreamlyWithSender so the resolved series is available during streaming; then call providerInfo.ModelDriver.ChatStreamlyWithSender(...) with the updated modelConfig/apiConfig containing the ModelSeries.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@internal/entity/model.go`:
- Around line 260-266: The code in the model initialization uses strings.Index
on model.Name and slices without guarding against a missing '-' which can panic,
and it also incorrectly assigns provider.Name instead of provider.Series; update
the block that sets model.Series (referencing model.Name, model.Series,
provider.Series, provider.Name) to: if provider.Series is non-empty, set
model.Series to pointer to provider.Series; else check that model.Name contains
a '-' (e.g., strings.Contains or checking Index >= 0) before slicing and only
then set model.Series to the substring before the hyphen; if there is no hyphen
and provider.Series is empty, leave model.Series nil or set a sensible default
to avoid panics and preserve the ChatConfig.ModelSeries parsing path.
In `@internal/entity/models/common.go`:
- Around line 21-27: GetThinkingAndAnswer currently dereferences modelSeries
without a nil check which can panic when ChatConfig.ModelSeries is unset; add a
nil check at the start of GetThinkingAndAnswer and if modelSeries == nil return
nil, content (preserving original content), otherwise switch on *modelSeries as
before and call extractThinkContent(content) for known series like "qwen3".
In `@internal/entity/models/gitee.go`:
- Around line 450-457: The code currently does a direct type assertion balance
:= result["balance"].(float64) which will panic for missing, null, string, or
non-number values; update the parsing in the function containing the
json.Unmarshal/result usage to validate the "balance" entry before asserting:
check that result["balance"] exists and is not nil, use a type switch or type
checks to accept float64 (and optionally parse numeric strings), and on any
other type or missing value return a provider parse error (e.g., fmt.Errorf with
clear context) instead of panicking; refer to the result map and the balance
variable in your changes.
- Around line 72-77: The routing check uses exact equality on modelSeries so
names like "qwen3" won't match; update the conditional around modelSeries
(derived from modelName) to use prefix matching instead (e.g.,
strings.HasPrefix(modelSeries, "qwen") || strings.HasPrefix(modelSeries, "glm"))
so qwen3-0.6b and glm-4.7 route to z.URLSuffix.AsyncChat via url =
fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.AsyncChat); reference
symbols: modelSeries, modelName, strings.HasPrefix, z.BaseURL,
z.URLSuffix.AsyncChat, region, url.
- Around line 271-273: The loop that handles streamed SSE payloads uses
scanner.Scan() and currently calls logger.Info(line), which logs raw model
output and can leak sensitive user content; remove that direct logging and
instead log only safe metadata (e.g., size or event type) or a
redacted/truncated placeholder when handling the variable line in the
scanner.Scan() loop, so replace logger.Info(line) with a non-sensitive log (for
example log length or "stream chunk received") and ensure no user-visible
content from line is written to application logs.
- Around line 197-211: The request currently defaults reqBody["stream"] to false
and hardcodes the path "/chat/completions", causing the SSE parser to receive
non-stream replies; update the url construction to use the provider-configured
suffix (e.g., replace the hardcoded "/chat/completions" with the configured
path/suffix from the client config) and change the reqBody default for "stream"
to true so streaming is enabled when chatModelConfig.Stream is nil; keep
honoring chatModelConfig.Stream when non-nil and ensure changes are applied
where url is built and reqBody is created (references: z.BaseURL, url variable,
reqBody map, and chatModelConfig.Stream).
In `@internal/service/model_service.go`:
- Around line 719-725: The code writes modelConfig.ModelSeries without checking
for nil; guard against a nil modelConfig before assigning ModelSeries by adding
a nil-check after retrieving model (from
dao.GetModelProviderManager().GetModelByName) and before modelConfig.ModelSeries
= model.Series: if modelConfig is nil, initialize it (e.g., set modelConfig =
&entity.ModelConfig{} or otherwise construct a default ModelConfig) so the
assignment is safe and downstream driver defaults can still be applied.
---
Outside diff comments:
In `@internal/service/model_service.go`:
- Around line 781-797: The resolved model's ModelSeries isn't being propagated
into the streaming path: change the call to GetModelByName to capture the
returned model info (e.g., modelInfo, err :=
dao.GetModelProviderManager().GetModelByName(providerName, modelName)), extract
its ModelSeries (modelInfo.ModelSeries) and set the same field used by the
non-streaming path (for example assign it into modelConfig.ModelSeries or
apiConfig.ModelSeries) before calling ChatStreamlyWithSender so the resolved
series is available during streaming; then call
providerInfo.ModelDriver.ChatStreamlyWithSender(...) with the updated
modelConfig/apiConfig containing the ModelSeries.
🪄 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: 524828e2-1653-437c-a1c7-3f1130b68943
📒 Files selected for processing (13)
conf/models/deepseek.jsonconf/models/minimax.jsonconf/models/moonshot.jsonconf/models/openai.jsonconf/models/xai.jsonconf/models/zhipu-ai.jsoninternal/entity/model.gointernal/entity/models/common.gointernal/entity/models/deepseek.gointernal/entity/models/factory.gointernal/entity/models/gitee.gointernal/entity/models/types.gointernal/service/model_service.go
| if provider.Series == "" { | ||
| pos := strings.Index(model.Name, "-") | ||
| modelSeries := model.Name[0:pos] | ||
| model.Series = &modelSeries | ||
| } else { | ||
| model.Series = &provider.Name | ||
| } |
There was a problem hiding this comment.
Use the configured series value and guard hyphenless model names.
Line 262 panics when a model name has no -, and Line 265 ignores provider.Series by assigning provider.Name. That breaks the new series-specific parsing path fed into ChatConfig.ModelSeries.
🐛 Proposed fix
- if provider.Series == "" {
- pos := strings.Index(model.Name, "-")
- modelSeries := model.Name[0:pos]
- model.Series = &modelSeries
- } else {
- model.Series = &provider.Name
- }
+ if provider.Series == "" {
+ pos := strings.Index(model.Name, "-")
+ modelSeries := model.Name
+ if pos > 0 {
+ modelSeries = model.Name[:pos]
+ }
+ model.Series = &modelSeries
+ } else {
+ modelSeries := provider.Series
+ model.Series = &modelSeries
+ }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/model.go` around lines 260 - 266, The code in the model
initialization uses strings.Index on model.Name and slices without guarding
against a missing '-' which can panic, and it also incorrectly assigns
provider.Name instead of provider.Series; update the block that sets
model.Series (referencing model.Name, model.Series, provider.Series,
provider.Name) to: if provider.Series is non-empty, set model.Series to pointer
to provider.Series; else check that model.Name contains a '-' (e.g.,
strings.Contains or checking Index >= 0) before slicing and only then set
model.Series to the substring before the hyphen; if there is no hyphen and
provider.Series is empty, leave model.Series nil or set a sensible default to
avoid panics and preserve the ChatConfig.ModelSeries parsing path.
| func GetThinkingAndAnswer(modelSeries *string, content *string) (*string, *string) { | ||
| switch *modelSeries { | ||
| case "qwen3": | ||
| return extractThinkContent(content) | ||
| } | ||
| return nil, content | ||
| } |
There was a problem hiding this comment.
Avoid panics when ModelSeries is unset.
ChatConfig.ModelSeries is optional, but Line 22 dereferences it unconditionally. A missing series should fall back to returning the original content, not panic the chat request.
🛡️ Proposed fix
func GetThinkingAndAnswer(modelSeries *string, content *string) (*string, *string) {
+ if content == nil {
+ return nil, nil
+ }
+ if modelSeries == nil {
+ return nil, content
+ }
switch *modelSeries {
case "qwen3":
return extractThinkContent(content)
}
return nil, content
}📝 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.
| func GetThinkingAndAnswer(modelSeries *string, content *string) (*string, *string) { | |
| switch *modelSeries { | |
| case "qwen3": | |
| return extractThinkContent(content) | |
| } | |
| return nil, content | |
| } | |
| func GetThinkingAndAnswer(modelSeries *string, content *string) (*string, *string) { | |
| if content == nil { | |
| return nil, nil | |
| } | |
| if modelSeries == nil { | |
| return nil, content | |
| } | |
| switch *modelSeries { | |
| case "qwen3": | |
| return extractThinkContent(content) | |
| } | |
| return nil, content | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/models/common.go` around lines 21 - 27, GetThinkingAndAnswer
currently dereferences modelSeries without a nil check which can panic when
ChatConfig.ModelSeries is unset; add a nil check at the start of
GetThinkingAndAnswer and if modelSeries == nil return nil, content (preserving
original content), otherwise switch on *modelSeries as before and call
extractThinkContent(content) for known series like "qwen3".
| // I need to get the model series, such as qwen3 is the prefix, the model series will be qwen. glm is the prefix, the model series will be glm. such as the model name: qwen3-0.6b, the model series will be qwen3 | ||
| // the model name is glm-4.7, the model series will be glm | ||
| modelSeries := strings.Split(*modelName, "-")[0] | ||
| if modelSeries == "qwen" || modelSeries == "glm" { | ||
| url = fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.AsyncChat) | ||
| } |
There was a problem hiding this comment.
Fix qwen routing to match actual model prefixes.
For qwen3-0.6b, Line 74 sets modelSeries to qwen3, so Line 75 does not route it to AsyncChat. Use prefix checks or compare against the expected concrete series.
🐛 Proposed fix
- modelSeries := strings.Split(*modelName, "-")[0]
- if modelSeries == "qwen" || modelSeries == "glm" {
+ if strings.HasPrefix(*modelName, "qwen") || strings.HasPrefix(*modelName, "glm") {
url = fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.AsyncChat)
}📝 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.
| // I need to get the model series, such as qwen3 is the prefix, the model series will be qwen. glm is the prefix, the model series will be glm. such as the model name: qwen3-0.6b, the model series will be qwen3 | |
| // the model name is glm-4.7, the model series will be glm | |
| modelSeries := strings.Split(*modelName, "-")[0] | |
| if modelSeries == "qwen" || modelSeries == "glm" { | |
| url = fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.AsyncChat) | |
| } | |
| // I need to get the model series, such as qwen3 is the prefix, the model series will be qwen. glm is the prefix, the model series will be glm. such as the model name: qwen3-0.6b, the model series will be qwen3 | |
| // the model name is glm-4.7, the model series will be glm | |
| if strings.HasPrefix(*modelName, "qwen") || strings.HasPrefix(*modelName, "glm") { | |
| url = fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.AsyncChat) | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/models/gitee.go` around lines 72 - 77, The routing check uses
exact equality on modelSeries so names like "qwen3" won't match; update the
conditional around modelSeries (derived from modelName) to use prefix matching
instead (e.g., strings.HasPrefix(modelSeries, "qwen") ||
strings.HasPrefix(modelSeries, "glm")) so qwen3-0.6b and glm-4.7 route to
z.URLSuffix.AsyncChat via url = fmt.Sprintf("%s/%s", z.BaseURL[region],
z.URLSuffix.AsyncChat); reference symbols: modelSeries, modelName,
strings.HasPrefix, z.BaseURL, z.URLSuffix.AsyncChat, region, url.
| url := fmt.Sprintf("%s/chat/completions", z.BaseURL[region]) | ||
|
|
||
| // Build request body with streaming enabled | ||
| reqBody := map[string]interface{}{ | ||
| "model": modelName, | ||
| "messages": []map[string]string{ | ||
| {"role": "user", "content": *message}, | ||
| }, | ||
| "stream": false, | ||
| "temperature": 1, | ||
| } | ||
|
|
||
| if chatModelConfig.Stream != nil { | ||
| reqBody["stream"] = *chatModelConfig.Stream | ||
| } |
There was a problem hiding this comment.
Force streaming requests to actually stream.
This method parses SSE, but Line 205 defaults "stream" to false; when chatModelConfig.Stream is nil, the provider can return normal JSON and the method emits only [DONE]. Also prefer the configured suffix over the hardcoded path.
🐛 Proposed fix
- url := fmt.Sprintf("%s/chat/completions", z.BaseURL[region])
+ url := fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.Chat)
// Build request body with streaming enabled
reqBody := map[string]interface{}{
"model": modelName,
"messages": []map[string]string{
{"role": "user", "content": *message},
},
- "stream": false,
+ "stream": true,
"temperature": 1,
}
- if chatModelConfig.Stream != nil {
- reqBody["stream"] = *chatModelConfig.Stream
- }
-🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/models/gitee.go` around lines 197 - 211, The request
currently defaults reqBody["stream"] to false and hardcodes the path
"/chat/completions", causing the SSE parser to receive non-stream replies;
update the url construction to use the provider-configured suffix (e.g., replace
the hardcoded "/chat/completions" with the configured path/suffix from the
client config) and change the reqBody default for "stream" to true so streaming
is enabled when chatModelConfig.Stream is nil; keep honoring
chatModelConfig.Stream when non-nil and ensure changes are applied where url is
built and reqBody is created (references: z.BaseURL, url variable, reqBody map,
and chatModelConfig.Stream).
| // Parse response | ||
| var result map[string]interface{} | ||
| if err = json.Unmarshal(body, &result); err != nil { | ||
| return nil, fmt.Errorf("failed to parse response: %w", err) | ||
| } | ||
|
|
||
| balance := result["balance"].(float64) | ||
|
|
There was a problem hiding this comment.
Validate the balance field before type assertion.
Line 456 panics if Gitee returns a missing, null, string, or error-shaped balance. Return a provider parse error instead.
🐛 Proposed fix
- balance := result["balance"].(float64)
+ balance, ok := result["balance"].(float64)
+ if !ok {
+ return nil, fmt.Errorf("invalid balance format")
+ }📝 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.
| // Parse response | |
| var result map[string]interface{} | |
| if err = json.Unmarshal(body, &result); err != nil { | |
| return nil, fmt.Errorf("failed to parse response: %w", err) | |
| } | |
| balance := result["balance"].(float64) | |
| // Parse response | |
| var result map[string]interface{} | |
| if err = json.Unmarshal(body, &result); err != nil { | |
| return nil, fmt.Errorf("failed to parse response: %w", err) | |
| } | |
| balance, ok := result["balance"].(float64) | |
| if !ok { | |
| return nil, fmt.Errorf("invalid balance format") | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/models/gitee.go` around lines 450 - 457, The code currently
does a direct type assertion balance := result["balance"].(float64) which will
panic for missing, null, string, or non-number values; update the parsing in the
function containing the json.Unmarshal/result usage to validate the "balance"
entry before asserting: check that result["balance"] exists and is not nil, use
a type switch or type checks to accept float64 (and optionally parse numeric
strings), and on any other type or missing value return a provider parse error
(e.g., fmt.Errorf with clear context) instead of panicking; refer to the result
map and the balance variable in your changes.
| var model *entity.Model = nil | ||
| model, err = dao.GetModelProviderManager().GetModelByName(providerName, modelName) | ||
| if err != nil { | ||
| return nil, common.CodeNotFound, errors.New(fmt.Sprintf("provider %s model %s not found", providerName, modelName)) | ||
| } | ||
|
|
||
| modelConfig.ModelSeries = model.Series |
There was a problem hiding this comment.
Guard modelConfig before writing ModelSeries.
Line 725 now dereferences modelConfig; a nil config will panic before the driver can apply defaults.
Proposed fix
var model *entity.Model = nil
model, err = dao.GetModelProviderManager().GetModelByName(providerName, modelName)
if err != nil {
return nil, common.CodeNotFound, errors.New(fmt.Sprintf("provider %s model %s not found", providerName, modelName))
}
+ if modelConfig == nil {
+ modelConfig = &modelModule.ChatConfig{}
+ }
modelConfig.ModelSeries = model.Series📝 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 model *entity.Model = nil | |
| model, err = dao.GetModelProviderManager().GetModelByName(providerName, modelName) | |
| if err != nil { | |
| return nil, common.CodeNotFound, errors.New(fmt.Sprintf("provider %s model %s not found", providerName, modelName)) | |
| } | |
| modelConfig.ModelSeries = model.Series | |
| var model *entity.Model = nil | |
| model, err = dao.GetModelProviderManager().GetModelByName(providerName, modelName) | |
| if err != nil { | |
| return nil, common.CodeNotFound, errors.New(fmt.Sprintf("provider %s model %s not found", providerName, modelName)) | |
| } | |
| if modelConfig == nil { | |
| modelConfig = &modelModule.ChatConfig{} | |
| } | |
| modelConfig.ModelSeries = model.Series |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/service/model_service.go` around lines 719 - 725, The code writes
modelConfig.ModelSeries without checking for nil; guard against a nil
modelConfig before assigning ModelSeries by adding a nil-check after retrieving
model (from dao.GetModelProviderManager().GetModelByName) and before
modelConfig.ModelSeries = model.Series: if modelConfig is nil, initialize it
(e.g., set modelConfig = &entity.ModelConfig{} or otherwise construct a default
ModelConfig) so the assignment is safe and downstream driver defaults can still
be applied.
There was a problem hiding this comment.
Actionable comments posted: 3
♻️ Duplicate comments (4)
internal/entity/models/gitee.go (4)
72-77:⚠️ Potential issue | 🟠 MajorFix qwen routing to match actual model prefixes.
qwen3-0.6bproducesmodelSeries == "qwen3", so Line 75 still skips the async endpoint.🐛 Proposed fix
modelSeries := strings.Split(*modelName, "-")[0] - if modelSeries == "qwen" || modelSeries == "glm" { + if strings.HasPrefix(modelSeries, "qwen") || strings.HasPrefix(modelSeries, "glm") { url = fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.AsyncChat) }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/entity/models/gitee.go` around lines 72 - 77, The routing check uses an exact equality on modelSeries which fails for prefixes like "qwen3"; update the conditional that decides the async endpoint (the block using modelSeries and assigning url with fmt.Sprintf and z.URLSuffix.AsyncChat) to match prefix-based names (e.g., use strings.HasPrefix(modelSeries, "qwen") || modelSeries == "glm") so "qwen3-0.6b" yields the async URL; keep the existing modelSeries extraction via strings.Split(*modelName, "-")[0].
197-211:⚠️ Potential issue | 🟠 MajorForce streaming requests to actually stream.
This method parses SSE, but Line 205 defaults
"stream"tofalse; if the caller leaveschatModelConfig.Streamnil, the method can receive normal JSON and emit only[DONE]. Also use the configured suffix instead of hardcoding the path.🐛 Proposed fix
- url := fmt.Sprintf("%s/chat/completions", z.BaseURL[region]) + url := fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.Chat) // Build request body with streaming enabled reqBody := map[string]interface{}{ "model": modelName, "messages": []map[string]string{ {"role": "user", "content": *message}, }, - "stream": false, + "stream": true, "temperature": 1, }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/entity/models/gitee.go` around lines 197 - 211, The code currently builds reqBody with "stream" defaulting to false and constructs url using a hardcoded "/chat/completions"; change the default to enable SSE and use the configured suffix instead of the hardcoded path: set reqBody["stream"] = true unless chatModelConfig.Stream is non-nil (honor *chatModelConfig.Stream when provided) and construct url by joining z.BaseURL[region] with the configured suffix variable (use the existing suffix/config field used elsewhere in this package) rather than hardcoding "/chat/completions"; update references to reqBody, chatModelConfig.Stream, url and z.BaseURL to reflect these changes.
271-273:⚠️ Potential issue | 🟠 MajorDo not log raw streamed model output.
logger.Info(line)records every SSE payload, including user prompts, generated content, and reasoning data.🛡️ Proposed fix
for scanner.Scan() { line := scanner.Text() - logger.Info(line) // SSE data line starts with "data:"🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/entity/models/gitee.go` around lines 271 - 273, The loop that processes SSE payloads currently logs every raw streamed line via logger.Info(line) inside the scanner.Scan() loop; remove or replace that call so raw model outputs and user prompts are not written to logs—either delete logger.Info(line) or replace it with a scrubbed/metadata-only log (e.g., log event type, payload length, or a redacted summary) in the scanner.Scan() block where line is read; update any tests or callers relying on that log and ensure the change is applied where scanner.Scan(), line, and logger.Info are used in gitee.go.
445-445:⚠️ Potential issue | 🟠 MajorValidate the balance field before type assertion.
A missing, null, string, or error-shaped
balancefield will panic here instead of returning a parse error.🐛 Proposed fix
- balance := result["balance"].(float64) + balance, ok := result["balance"].(float64) + if !ok { + return nil, fmt.Errorf("invalid balance format") + }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/entity/models/gitee.go` at line 445, The code does an unchecked type assertion on result["balance"] (balance := result["balance"].(float64)), which will panic if the key is missing, null, a string, or an unexpected shape; update the parsing logic to first test presence and type using a type switch or ok-style checks (e.g., check value, ok := result["balance"]; handle nil), handle numeric strings by parsing if needed, and return a clear parse error instead of panicking; adjust the function that builds the Gitee model (the code that reads result and assigns balance) to validate and convert the balance field safely and propagate a descriptive error on failure.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@internal/entity/models/gitee.go`:
- Line 60: Validate all pointer parameters before dereferencing: in
GiteeModel.Chat check that modelName, message, apiConfig, apiConfig.ApiKey and
chatModelConfig are non-nil (and that strings are non-empty) and return a
provider error instead of panicking; apply the same guard pattern to the other
GiteeModel methods referenced (streaming, list, balance, status) so each method
first validates apiConfig and chatModelConfig and returns a clear provider error
when configuration or keys are missing.
- Line 175: Guard against a nil chatModelConfig.ModelSeries before calling
GetThinkingAndAnswer: if chatModelConfig.ModelSeries is nil, pass a pointer to
the parsed local modelSeries variable instead of dereferencing a nil pointer.
Concretely, compute a local pointer variable (e.g., seriesPtr) that is
chatModelConfig.ModelSeries if non-nil or &modelSeries as a fallback, then call
GetThinkingAndAnswer(modelSeriesConfig.ModelSeries...) using that pointer (use
the same symbol names GetThinkingAndAnswer, chatModelConfig.ModelSeries, and
modelSeries to locate where to change).
- Around line 329-335: The code currently sends the "[DONE]" endOfStream marker
unconditionally then returns scanner.Err(), which can hide mid-stream errors;
change the flow in the function/method that uses sender and scanner so you call
scanner.Err() first and if it returns a non-nil error return that error
immediately, and only call sender(&endOfStream, nil) when scanner.Err() is nil;
reference the existing symbols sender, scanner, and endOfStream to locate and
update the logic so the completion marker is sent only after confirming there
was no scanning error.
---
Duplicate comments:
In `@internal/entity/models/gitee.go`:
- Around line 72-77: The routing check uses an exact equality on modelSeries
which fails for prefixes like "qwen3"; update the conditional that decides the
async endpoint (the block using modelSeries and assigning url with fmt.Sprintf
and z.URLSuffix.AsyncChat) to match prefix-based names (e.g., use
strings.HasPrefix(modelSeries, "qwen") || modelSeries == "glm") so "qwen3-0.6b"
yields the async URL; keep the existing modelSeries extraction via
strings.Split(*modelName, "-")[0].
- Around line 197-211: The code currently builds reqBody with "stream"
defaulting to false and constructs url using a hardcoded "/chat/completions";
change the default to enable SSE and use the configured suffix instead of the
hardcoded path: set reqBody["stream"] = true unless chatModelConfig.Stream is
non-nil (honor *chatModelConfig.Stream when provided) and construct url by
joining z.BaseURL[region] with the configured suffix variable (use the existing
suffix/config field used elsewhere in this package) rather than hardcoding
"/chat/completions"; update references to reqBody, chatModelConfig.Stream, url
and z.BaseURL to reflect these changes.
- Around line 271-273: The loop that processes SSE payloads currently logs every
raw streamed line via logger.Info(line) inside the scanner.Scan() loop; remove
or replace that call so raw model outputs and user prompts are not written to
logs—either delete logger.Info(line) or replace it with a scrubbed/metadata-only
log (e.g., log event type, payload length, or a redacted summary) in the
scanner.Scan() block where line is read; update any tests or callers relying on
that log and ensure the change is applied where scanner.Scan(), line, and
logger.Info are used in gitee.go.
- Line 445: The code does an unchecked type assertion on result["balance"]
(balance := result["balance"].(float64)), which will panic if the key is
missing, null, a string, or an unexpected shape; update the parsing logic to
first test presence and type using a type switch or ok-style checks (e.g., check
value, ok := result["balance"]; handle nil), handle numeric strings by parsing
if needed, and return a clear parse error instead of panicking; adjust the
function that builds the Gitee model (the code that reads result and assigns
balance) to validate and convert the balance field safely and propagate a
descriptive error on failure.
🪄 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: 4e517b7c-2ec1-4d27-a728-37c5b5e2bcf8
📒 Files selected for processing (1)
internal/entity/models/gitee.go
| } | ||
|
|
||
| // Chat sends a message and returns response | ||
| func (z *GiteeModel) Chat(modelName, message *string, apiConfig *APIConfig, chatModelConfig *ChatConfig) (*ChatResponse, error) { |
There was a problem hiding this comment.
Validate pointer inputs before dereferencing them.
These methods dereference modelName, message, apiConfig, apiConfig.ApiKey, and chatModelConfig on later lines. Missing configuration should return a provider error, not panic the caller.
🛡️ Proposed guard pattern
func (z *GiteeModel) Chat(modelName, message *string, apiConfig *APIConfig, chatModelConfig *ChatConfig) (*ChatResponse, error) {
+ if modelName == nil {
+ return nil, fmt.Errorf("modelName is nil")
+ }
if message == nil {
return nil, fmt.Errorf("message is nil")
}
+ if apiConfig == nil || apiConfig.ApiKey == nil {
+ return nil, fmt.Errorf("api key is nil")
+ }
+ if chatModelConfig == nil {
+ chatModelConfig = &ChatConfig{}
+ }Apply the same pattern to the streaming/list/balance/status methods before accessing apiConfig or chatModelConfig.
Also applies to: 191-191, 343-343, 400-400, 455-455
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/models/gitee.go` at line 60, Validate all pointer parameters
before dereferencing: in GiteeModel.Chat check that modelName, message,
apiConfig, apiConfig.ApiKey and chatModelConfig are non-nil (and that strings
are non-empty) and return a provider error instead of panicking; apply the same
guard pattern to the other GiteeModel methods referenced (streaming, list,
balance, status) so each method first validates apiConfig and chatModelConfig
and returns a clear provider error when configuration or keys are missing.
| return nil, fmt.Errorf("invalid content format") | ||
| } | ||
|
|
||
| thinking, answer := GetThinkingAndAnswer(chatModelConfig.ModelSeries, &content) |
There was a problem hiding this comment.
Guard ModelSeries before calling GetThinkingAndAnswer.
GetThinkingAndAnswer dereferences *modelSeries in internal/entity/models/common.go, so a nil chatModelConfig.ModelSeries panics. Use the parsed local modelSeries as a fallback.
🐛 Proposed fix
- thinking, answer := GetThinkingAndAnswer(chatModelConfig.ModelSeries, &content)
+ series := chatModelConfig.ModelSeries
+ if series == nil {
+ series = &modelSeries
+ }
+ thinking, answer := GetThinkingAndAnswer(series, &content)📝 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.
| thinking, answer := GetThinkingAndAnswer(chatModelConfig.ModelSeries, &content) | |
| series := chatModelConfig.ModelSeries | |
| if series == nil { | |
| series = &modelSeries | |
| } | |
| thinking, answer := GetThinkingAndAnswer(series, &content) |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/models/gitee.go` at line 175, Guard against a nil
chatModelConfig.ModelSeries before calling GetThinkingAndAnswer: if
chatModelConfig.ModelSeries is nil, pass a pointer to the parsed local
modelSeries variable instead of dereferencing a nil pointer. Concretely, compute
a local pointer variable (e.g., seriesPtr) that is chatModelConfig.ModelSeries
if non-nil or &modelSeries as a fallback, then call
GetThinkingAndAnswer(modelSeriesConfig.ModelSeries...) using that pointer (use
the same symbol names GetThinkingAndAnswer, chatModelConfig.ModelSeries, and
modelSeries to locate where to change).
| // Send [DONE] marker for OpenAI compatibility | ||
| endOfStream := "[DONE]" | ||
| if err = sender(&endOfStream, nil); err != nil { | ||
| return err | ||
| } | ||
|
|
||
| return scanner.Err() |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Verify Go's bufio.Scanner exposes deferred scan/read errors through Scanner.Err.
go doc bufio.Scanner.Err | sed -n '1,80p'Repository: infiniflow/ragflow
Length of output: 202
🏁 Script executed:
cd /tmp && git clone https://github.com/infiniflow/ragflow.git 2>/dev/null && cd ragflow && pwdRepository: infiniflow/ragflow
Length of output: 74
🏁 Script executed:
# Read the specific lines mentioned in the review
head -n 340 internal/entity/models/gitee.go | tail -n 20Repository: infiniflow/ragflow
Length of output: 610
🏁 Script executed:
# Get more context around those lines to understand the function
head -n 350 internal/entity/models/gitee.go | tail -n 40Repository: infiniflow/ragflow
Length of output: 1093
🏁 Script executed:
# Search for the sender function definition
rg -n "func.*sender" internal/entity/models/gitee.go -A 5Repository: infiniflow/ragflow
Length of output: 340
🏁 Script executed:
# Check what this function is doing - get the entire function containing these lines
ast-grep --pattern $'func $$$() {
$$$
scanner.Scan()
$$$
}'Repository: infiniflow/ragflow
Length of output: 44
Check stream errors before sending [DONE].
If the scanner encounters an error mid-stream (e.g., network failure), the current code still sends the [DONE] marker first, causing callers to treat a truncated/failed response as successful completion. The error is only returned after the completion signal is sent.
🐛 Proposed fix
- // Send [DONE] marker for OpenAI compatibility
+ if err := scanner.Err(); err != nil {
+ return fmt.Errorf("failed to read stream: %w", err)
+ }
+
+ // Send [DONE] marker for OpenAI compatibility
endOfStream := "[DONE]"
if err = sender(&endOfStream, nil); err != nil {
return err
}
- return scanner.Err()
+ return nil📝 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.
| // Send [DONE] marker for OpenAI compatibility | |
| endOfStream := "[DONE]" | |
| if err = sender(&endOfStream, nil); err != nil { | |
| return err | |
| } | |
| return scanner.Err() | |
| if err := scanner.Err(); err != nil { | |
| return fmt.Errorf("failed to read stream: %w", err) | |
| } | |
| // Send [DONE] marker for OpenAI compatibility | |
| endOfStream := "[DONE]" | |
| if err = sender(&endOfStream, nil); err != nil { | |
| return err | |
| } | |
| return nil |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/models/gitee.go` around lines 329 - 335, The code currently
sends the "[DONE]" endOfStream marker unconditionally then returns
scanner.Err(), which can hide mid-stream errors; change the flow in the
function/method that uses sender and scanner so you call scanner.Err() first and
if it returns a non-nil error return that error immediately, and only call
sender(&endOfStream, nil) when scanner.Err() is nil; reference the existing
symbols sender, scanner, and endOfStream to locate and update the logic so the
completion marker is sent only after confirming there was no scanning error.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14336 +/- ##
=======================================
Coverage 95.30% 95.30%
=======================================
Files 10 10
Lines 703 703
Branches 112 112
=======================================
Hits 670 670
Misses 16 16
Partials 17 17 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (7)
internal/entity/models/gitee.go (7)
351-357:⚠️ Potential issue | 🟠 MajorUnresolved:
scanner.Err()should be checked before sending[DONE].If the SSE stream fails mid-flight, the current flow still emits the completion marker, causing callers to treat a truncated response as a successful completion.
🐛 Proposed fix
+ if err := scanner.Err(); err != nil { + return fmt.Errorf("failed to read stream: %w", err) + } + // Send [DONE] marker for OpenAI compatibility endOfStream := "[DONE]" if err = sender(&endOfStream, nil); err != nil { return err } - - return scanner.Err() + return nil🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/entity/models/gitee.go` around lines 351 - 357, The code currently sends the "[DONE]" marker before checking scanner.Err(), which can signal successful completion for a truncated SSE stream; move the scanner error check to occur before sending the endOfStream marker: after the scanning loop call scanner.Err(), if non-nil return that error immediately, and only if scanner.Err() is nil construct endOfStream ("[DONE]") and call sender(&endOfStream, nil); ensure the same sender/endOfStream variables are used and that the function returns any scanner error instead of sending the completion marker on failure.
60-68:⚠️ Potential issue | 🟠 MajorUnresolved: nil pointer guards still missing for
modelName,apiConfig,apiConfig.ApiKey, andchatModelConfig.Lines 66, 74, 81, 83, 89, 132 dereference pointers that are not validated. A missing API key or model name will panic the caller instead of returning a provider error. Apply the same guard pattern to
ChatStreamlyWithSender,ListModels,Balance, andCheckConnection.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/entity/models/gitee.go` around lines 60 - 68, Add nil-pointer guards to avoid panics: in GiteeModel.Chat validate modelName, apiConfig, apiConfig.ApiKey, and chatModelConfig at the start (similar to the existing message nil check) and return a descriptive error when any is nil or empty; apply the same validation pattern to the other methods named ChatStreamlyWithSender, ListModels, Balance, and CheckConnection so they check and return provider errors instead of dereferencing nil pointers. Ensure each check references the exact parameter names (modelName, apiConfig, apiConfig.ApiKey, chatModelConfig) and returns an appropriate error message before any dereferences occur.
175-175:⚠️ Potential issue | 🔴 CriticalUnresolved: nil
ModelSerieswill panic insideGetThinkingAndAnswer.Per
internal/entity/models/common.go,GetThinkingAndAnswerunconditionally doesswitch *modelSeries. Fall back to the locally parsed series whenchatModelConfig.ModelSeriesis nil.🐛 Proposed fix
- thinking, answer := GetThinkingAndAnswer(chatModelConfig.ModelSeries, &content) + series := chatModelConfig.ModelSeries + if series == nil { + series = &modelSeries + } + thinking, answer := GetThinkingAndAnswer(series, &content)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/entity/models/gitee.go` at line 175, Get rid of the potential nil dereference by passing a non-nil ModelSeries into GetThinkingAndAnswer: check if chatModelConfig.ModelSeries is nil and if so pass the locally parsed modelSeries (e.g., use &modelSeries) instead of chatModelConfig.ModelSeries; update the call to GetThinkingAndAnswer(chatModelConfig.ModelSeries ?? &modelSeries, &content) logic so GetThinkingAndAnswer never receives a nil pointer.
192-206:⚠️ Potential issue | 🟠 MajorUnresolved: streaming method still defaults
streamtofalseand hardcodes the URL path.The SSE parser below assumes streamed responses, but with
stream: false(andchatModelConfig.Stream == nil), Gitee returns a single JSON body and this method emits only the terminal[DONE]. Also preferz.URLSuffix.Chat/AsyncChatover the hardcoded suffix so the same routing used inChat()applies here.🐛 Proposed fix
- url := fmt.Sprintf("%s/chat/completions", z.BaseURL[region]) + url := fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.Chat) + if strings.HasPrefix(*modelName, "qwen") || strings.HasPrefix(*modelName, "glm") { + url = fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.AsyncChat) + } // Build request body with streaming enabled reqBody := map[string]interface{}{ "model": modelName, "messages": []map[string]string{ {"role": "user", "content": *message}, }, - "stream": false, + "stream": true, "temperature": 1, } - - if chatModelConfig.Stream != nil { - reqBody["stream"] = *chatModelConfig.Stream - }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/entity/models/gitee.go` around lines 192 - 206, The code builds reqBody with "stream" defaulting to false and hardcodes the path suffix; change it so "stream" defaults to true (so the SSE parser receives streamed responses) unless chatModelConfig.Stream is explicitly set, and construct url using z.URLSuffix.AsyncChat when streaming (true) or z.URLSuffix.Chat when not, instead of the hardcoded "/chat/completions"; update the variables used in this block (url, reqBody, chatModelConfig.Stream, z.BaseURL, z.URLSuffix.Chat, z.URLSuffix.AsyncChat) accordingly so routing matches the Chat() behavior and the SSE parser receives proper streamed responses.
467-467:⚠️ Potential issue | 🟠 MajorUnresolved: unchecked type assertion on
balancewill panic.If Gitee returns a missing/null/string/object
balancefield,result["balance"].(float64)panics. Return a parse error instead.🐛 Proposed fix
- balance := result["balance"].(float64) + balance, ok := result["balance"].(float64) + if !ok { + return nil, fmt.Errorf("invalid balance format in response: %v", result["balance"]) + }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/entity/models/gitee.go` at line 467, The unchecked type assertion balance := result["balance"].(float64) can panic for nil/missing/non-float values; replace it with a safe type check (e.g., use a type switch or comma-ok assertion on result["balance"]) that handles float64, numeric string, int types and nil, and on any other case returns a parse error; update the surrounding function (the code that reads from result map and uses variable balance) to use the validated/converted value and return the parse error when the balance cannot be parsed.
72-77:⚠️ Potential issue | 🟠 MajorUnresolved: qwen/glm routing still uses exact equality and misses
qwen3-*,qwen2.5-*, etc.
strings.Split("qwen3-0.6b", "-")[0]is"qwen3", which does not equal"qwen", so the AsyncChat URL is never selected. Use prefix matching on*modelNamedirectly.🐛 Proposed fix
- modelSeries := strings.Split(*modelName, "-")[0] - if modelSeries == "qwen" || modelSeries == "glm" { + if strings.HasPrefix(*modelName, "qwen") || strings.HasPrefix(*modelName, "glm") { url = fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.AsyncChat) }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/entity/models/gitee.go` around lines 72 - 77, The routing logic incorrectly uses exact equality on modelSeries (calculated as strings.Split(*modelName, "-")[0]) so names like "qwen3-0.6b" or "qwen2.5-*" won't match "qwen" or "glm"; update the condition to use prefix matching against *modelName (or modelSeries prefix) instead of equality — e.g., check strings.HasPrefix(*modelName, "qwen") || strings.HasPrefix(*modelName, "glm") — and keep the same behavior of setting url = fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.AsyncChat) when a prefix match succeeds (refer to modelName, modelSeries, z.BaseURL and z.URLSuffix.AsyncChat in internal/entity/models/gitee.go).
272-272:⚠️ Potential issue | 🟠 MajorUnresolved: raw SSE payload still logged at Info level.
Despite the previous review being marked addressed,
logger.Info(line)remains and will emit user content and reasoning into application logs (PII/privacy concern). Drop it or downgrade to Debug with a size/event-type summary only.🛡️ Proposed fix
line := scanner.Text() - logger.Info(line) // SSE data line starts with "data:"🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/entity/models/gitee.go` at line 272, The code currently emits raw SSE payloads via logger.Info(line), which exposes user content; remove that logger.Info(line) call or downgrade it to a debug-only summary. Replace it with a logger.Debug/Debugf that logs only non-sensitive metadata (e.g., event type and payload size using the 'line' variable) or omit logging entirely; ensure no raw payload content is written at Info level.
🧹 Nitpick comments (2)
internal/entity/models/gitee.go (2)
374-381: Avoid sending a body with GET requests.
ListModels,Balance, andCheckConnectionmarshal an empty map and passbytes.NewBuffer(jsonData)as the body tohttp.NewRequest("GET", ...). Some gateways and proxies reject or mangle GETs with bodies. Passnil:- reqBody := map[string]interface{}{} - - jsonData, err := json.Marshal(reqBody) - if err != nil { - return nil, fmt.Errorf("failed to marshal request: %w", err) - } - - req, err := http.NewRequest("GET", url, bytes.NewBuffer(jsonData)) + req, err := http.NewRequest("GET", url, nil)Also applies to: 431-438, 486-493
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/entity/models/gitee.go` around lines 374 - 381, The GET handlers (ListModels, Balance, CheckConnection) currently marshal an empty map and call http.NewRequest("GET", url, bytes.NewBuffer(jsonData)), which can break through some gateways; remove the empty-body marshalling and pass nil as the request body to http.NewRequest for those GET requests instead (i.e., replace bytes.NewBuffer(jsonData) with nil and drop the json.Marshal of an empty map), and apply the same change to the other occurrences mentioned (the http.NewRequest calls around the areas flagged).
331-332: Collapse the twoTrimcalls.- content = strings.Trim(content, "\n") - content = strings.Trim(content, " ") + content = strings.TrimSpace(content)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/entity/models/gitee.go` around lines 331 - 332, The two successive trims on the variable content (strings.Trim(content, "\n") then strings.Trim(content, " ")) should be collapsed into a single call: replace both with strings.TrimSpace(content) (or a single strings.Trim(content, " \n") if explicit chars are preferred) wherever content is normalized in this code path to avoid redundant operations and clarify intent.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@internal/entity/models/gitee.go`:
- Around line 264-349: The stream handling concatenates all chunks into
reserveText because thinkingPhase and answerPhase default to false and
delta.reasoning_content is ignored; update the SSE loop in the function that
reads resp.Body (referencing variables thinkingPhase, answerPhase, reserveText,
sender, delta, content, and finish_reason) so that for non-qwen3 models (use
chatModelConfig.ModelSeries) you either set answerPhase = true by default OR
immediately call sender(&content, nil) when neither phase is active instead of
appending to reserveText; also detect and handle delta["reasoning_content"]
alongside delta["content"] (treat it like thinking content or stream it
appropriately), and ensure any remaining reserveText is only used as a fallback
flush at the end.
---
Duplicate comments:
In `@internal/entity/models/gitee.go`:
- Around line 351-357: The code currently sends the "[DONE]" marker before
checking scanner.Err(), which can signal successful completion for a truncated
SSE stream; move the scanner error check to occur before sending the endOfStream
marker: after the scanning loop call scanner.Err(), if non-nil return that error
immediately, and only if scanner.Err() is nil construct endOfStream ("[DONE]")
and call sender(&endOfStream, nil); ensure the same sender/endOfStream variables
are used and that the function returns any scanner error instead of sending the
completion marker on failure.
- Around line 60-68: Add nil-pointer guards to avoid panics: in GiteeModel.Chat
validate modelName, apiConfig, apiConfig.ApiKey, and chatModelConfig at the
start (similar to the existing message nil check) and return a descriptive error
when any is nil or empty; apply the same validation pattern to the other methods
named ChatStreamlyWithSender, ListModels, Balance, and CheckConnection so they
check and return provider errors instead of dereferencing nil pointers. Ensure
each check references the exact parameter names (modelName, apiConfig,
apiConfig.ApiKey, chatModelConfig) and returns an appropriate error message
before any dereferences occur.
- Line 175: Get rid of the potential nil dereference by passing a non-nil
ModelSeries into GetThinkingAndAnswer: check if chatModelConfig.ModelSeries is
nil and if so pass the locally parsed modelSeries (e.g., use &modelSeries)
instead of chatModelConfig.ModelSeries; update the call to
GetThinkingAndAnswer(chatModelConfig.ModelSeries ?? &modelSeries, &content)
logic so GetThinkingAndAnswer never receives a nil pointer.
- Around line 192-206: The code builds reqBody with "stream" defaulting to false
and hardcodes the path suffix; change it so "stream" defaults to true (so the
SSE parser receives streamed responses) unless chatModelConfig.Stream is
explicitly set, and construct url using z.URLSuffix.AsyncChat when streaming
(true) or z.URLSuffix.Chat when not, instead of the hardcoded
"/chat/completions"; update the variables used in this block (url, reqBody,
chatModelConfig.Stream, z.BaseURL, z.URLSuffix.Chat, z.URLSuffix.AsyncChat)
accordingly so routing matches the Chat() behavior and the SSE parser receives
proper streamed responses.
- Line 467: The unchecked type assertion balance := result["balance"].(float64)
can panic for nil/missing/non-float values; replace it with a safe type check
(e.g., use a type switch or comma-ok assertion on result["balance"]) that
handles float64, numeric string, int types and nil, and on any other case
returns a parse error; update the surrounding function (the code that reads from
result map and uses variable balance) to use the validated/converted value and
return the parse error when the balance cannot be parsed.
- Around line 72-77: The routing logic incorrectly uses exact equality on
modelSeries (calculated as strings.Split(*modelName, "-")[0]) so names like
"qwen3-0.6b" or "qwen2.5-*" won't match "qwen" or "glm"; update the condition to
use prefix matching against *modelName (or modelSeries prefix) instead of
equality — e.g., check strings.HasPrefix(*modelName, "qwen") ||
strings.HasPrefix(*modelName, "glm") — and keep the same behavior of setting url
= fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.AsyncChat) when a prefix
match succeeds (refer to modelName, modelSeries, z.BaseURL and
z.URLSuffix.AsyncChat in internal/entity/models/gitee.go).
- Line 272: The code currently emits raw SSE payloads via logger.Info(line),
which exposes user content; remove that logger.Info(line) call or downgrade it
to a debug-only summary. Replace it with a logger.Debug/Debugf that logs only
non-sensitive metadata (e.g., event type and payload size using the 'line'
variable) or omit logging entirely; ensure no raw payload content is written at
Info level.
---
Nitpick comments:
In `@internal/entity/models/gitee.go`:
- Around line 374-381: The GET handlers (ListModels, Balance, CheckConnection)
currently marshal an empty map and call http.NewRequest("GET", url,
bytes.NewBuffer(jsonData)), which can break through some gateways; remove the
empty-body marshalling and pass nil as the request body to http.NewRequest for
those GET requests instead (i.e., replace bytes.NewBuffer(jsonData) with nil and
drop the json.Marshal of an empty map), and apply the same change to the other
occurrences mentioned (the http.NewRequest calls around the areas flagged).
- Around line 331-332: The two successive trims on the variable content
(strings.Trim(content, "\n") then strings.Trim(content, " ")) should be
collapsed into a single call: replace both with strings.TrimSpace(content) (or a
single strings.Trim(content, " \n") if explicit chars are preferred) wherever
content is normalized in this code path to avoid redundant operations and
clarify intent.
🪄 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: 524ff4d1-e5c8-4edb-9c59-d276174a0897
📒 Files selected for processing (2)
internal/cli/user_command.gointernal/entity/models/gitee.go
| reserveText := "" | ||
| thinkingPhase := false | ||
| answerPhase := false | ||
|
|
||
| // SSE parsing: read line by line | ||
| scanner := bufio.NewScanner(resp.Body) | ||
| for scanner.Scan() { | ||
| line := scanner.Text() | ||
| logger.Info(line) | ||
|
|
||
| // SSE data line starts with "data:" | ||
| if !strings.HasPrefix(line, "data:") { | ||
| continue | ||
| } | ||
|
|
||
| // Extract JSON after "data:" | ||
| data := strings.TrimSpace(line[5:]) | ||
|
|
||
| // [DONE] marks the end of stream | ||
| if data == "[DONE]" { | ||
| break | ||
| } | ||
|
|
||
| // Parse the JSON event | ||
| var event map[string]interface{} | ||
| if err = json.Unmarshal([]byte(data), &event); err != nil { | ||
| continue | ||
| } | ||
|
|
||
| choices, ok := event["choices"].([]interface{}) | ||
| if !ok || len(choices) == 0 { | ||
| continue | ||
| } | ||
|
|
||
| firstChoice, ok := choices[0].(map[string]interface{}) | ||
| if !ok { | ||
| continue | ||
| } | ||
|
|
||
| delta, ok := firstChoice["delta"].(map[string]interface{}) | ||
| if !ok { | ||
| continue | ||
| } | ||
|
|
||
| content, ok := delta["content"].(string) | ||
| if ok && content != "" { | ||
| if content == "<think>" { | ||
| thinkingPhase = true | ||
| continue | ||
|
|
||
| } else if content == "</think>" { | ||
| thinkingPhase = false | ||
| answerPhase = true | ||
| continue | ||
| } | ||
|
|
||
| if thinkingPhase { | ||
| if err = sender(nil, &content); err != nil { | ||
| return err | ||
| } | ||
| reserveText = "" | ||
| } else if answerPhase { | ||
| if err = sender(&content, nil); err != nil { | ||
| return err | ||
| } | ||
| reserveText = "" | ||
| } else { | ||
| content = strings.Trim(content, "\n") | ||
| content = strings.Trim(content, " ") | ||
| if content != "" { | ||
| reserveText += content | ||
| } | ||
| } | ||
| } | ||
|
|
||
| finishReason, ok := firstChoice["finish_reason"].(string) | ||
| if ok && finishReason != "" { | ||
| break | ||
| } | ||
| } | ||
|
|
||
| if reserveText != "" { | ||
| if err = sender(&reserveText, nil); err != nil { | ||
| return err | ||
| } | ||
| } |
There was a problem hiding this comment.
Streaming is broken for models that don't emit <think>...</think> markers.
With thinkingPhase and answerPhase both starting false, any stream that never emits a literal <think> token (i.e. the common case — GPT-style models, DeepSeek reasoning via separate reasoning_content field, or any series other than qwen3) falls into the else branch at Line 330 on every chunk. All content is concatenated into reserveText and flushed only once at Line 345, so the caller receives a single chunk at end-of-stream instead of incremental tokens — the UX regresses to non-streaming.
Additionally, delta.reasoning_content (emitted by many OpenAI-compatible providers including DeepSeek/Qwen reasoning endpoints) is ignored entirely here.
Consider:
- Defaulting to
answerPhase = truefor models wherechatModelConfig.ModelSeriesis notqwen3, or - Streaming each chunk immediately as an answer fragment when neither phase is active, or
- Explicitly handling
delta.reasoning_contentin addition todelta.content.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/models/gitee.go` around lines 264 - 349, The stream handling
concatenates all chunks into reserveText because thinkingPhase and answerPhase
default to false and delta.reasoning_content is ignored; update the SSE loop in
the function that reads resp.Body (referencing variables thinkingPhase,
answerPhase, reserveText, sender, delta, content, and finish_reason) so that for
non-qwen3 models (use chatModelConfig.ModelSeries) you either set answerPhase =
true by default OR immediately call sender(&content, nil) when neither phase is
active instead of appending to reserveText; also detect and handle
delta["reasoning_content"] alongside delta["content"] (treat it like thinking
content or stream it appropriately), and ensure any remaining reserveText is
only used as a fallback flush at the end.
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 6
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
internal/handler/providers.go (2)
618-626:⚠️ Potential issue | 🟡 MinorBuilt-in
printlnmisuse here and at Line 673.Go's built-in
printlndoes not interpret format verbs — the literal string"JSON bind error: %v (type: %T)"will be printed with theerrvalues concatenated on stderr, not interpolated. This is a debug artifact and should use the project logger (or be removed) in bothEnableOrDisableModel(Line 620) andChatToModel(Line 673).Proposed fix (applies to both sites)
- println("JSON bind error: %v (type: %T)", err, err) + logger.Errorf("JSON bind error: %v (type: %T)", err, err)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/handler/providers.go` around lines 618 - 626, The debug uses Go's builtin println which doesn't format verbs and leaks a stray debug print; in both EnableOrDisableModel and ChatToModel replace the println("JSON bind error: %v (type: %T)", err, err) with the project's logger (e.g., processLogger.Errorf or the handler's logger) and log the formatted error and type, then keep the existing c.JSON BadRequest response path; remove the println calls entirely so only the structured logger reports the binding error for c.ShouldBindJSON in those handlers.
684-736:⚠️ Potential issue | 🟠 MajorFix asymmetry:
ChatToModelStreamWithSendershould setModelSerieslike the non-streaming path does.
ChatToModelStreamWithSender(lines 750–806) doesn't setmodelConfig.ModelSerieswhen callingChatStreamlyWithSender, whileChatToModelassignsmodelConfig.ModelSeries = model.Series(line 725) before callingChat().
GetThinkingAndAnswerdereferences*modelSerieswithout nil-checking (line 22 ofcommon.go), so any driver implementingChatStreamlyWithSenderthat callsGetThinkingAndAnswerwould NPE. Current drivers (SiliconFlow, Gitee) handle thinking/answer parsing internally, so the issue doesn't manifest today, but this asymmetry risks bugs in future drivers.Recommend setting
ModelSeriessymmetrically inChatToModelStreamWithSenderand/or makingGetThinkingAndAnswernil-safe.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/handler/providers.go` around lines 684 - 736, The stream path fails to set modelConfig.ModelSeries causing potential nil deref in GetThinkingAndAnswer; update ChatToModelStreamWithSender to mirror ChatToModel by assigning modelConfig.ModelSeries = model.Series (using the same model lookup used in the non-streaming path) before calling ChatStreamlyWithSender/ChatToModelStreamWithSender, or alternatively add a nil-check in GetThinkingAndAnswer for *modelSeries; prefer the first fix to keep behavior symmetric across ChatToModel and ChatToModelStreamWithSender and reference the symbols: ChatToModelStreamWithSender, ChatToModel, modelConfig.ModelSeries, ChatStreamlyWithSender, and GetThinkingAndAnswer.internal/cli/user_parser.go (1)
1671-1674:⚠️ Potential issue | 🟡 Minor
SET DEFAULT ... MODELstill advertises the oldprovider/instance/modelformat.The
CHATandUSE MODELcommands were switched to'model@instance@provider', but this branch retains the legacy wording in both the comment and the error message. If downstream consumers ofcomposite_model_namealso moved to@, users will receive a misleading error; if they didn't, the two commands diverge on the same parameter. Please align the format (and the error string) with the rest of the CLI, or intentionally document the difference.Proposed fix
- // Format: 'provider/instance/model' or just 'message' + // Format: 'model@instance@provider' if p.curToken.Type != TokenQuotedString { - return nil, fmt.Errorf("expected quoted string with format provider/instance/model") + return nil, fmt.Errorf("expected quoted string with format model@instance@provider") }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/cli/user_parser.go` around lines 1671 - 1674, Update the comment and error message that describe the expected composite model name format in the parsing branch that checks p.curToken.Type (the branch returning fmt.Errorf("expected quoted string with format provider/instance/model")); change the wording to match the new canonical format used elsewhere ("model@instance@provider") so the parser, its comment, and the error string all refer to composite_model_name using '@' rather than '/'. Locate the branch in user_parser.go where p.curToken.Type != TokenQuotedString is checked and replace the legacy description with the new '@' format for consistency with CHAT and USE MODEL.
🧹 Nitpick comments (4)
internal/entity/models/siliconflow.go (2)
381-384:http.NewRequest("GET", ..., bytes.NewBuffer(jsonData))sends an empty JSON body on a GET.Harmless today (body is
{}) but unusual — some gateways/proxies strip or reject GET bodies. Passingnilis idiomatic here.Proposed fix
- // Build request body - reqBody := map[string]interface{}{} - - jsonData, err := json.Marshal(reqBody) - if err != nil { - return nil, fmt.Errorf("failed to marshal request: %w", err) - } - - req, err := http.NewRequest("GET", url, bytes.NewBuffer(jsonData)) + req, err := http.NewRequest("GET", url, nil)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/entity/models/siliconflow.go` around lines 381 - 384, In siliconflow.go change the GET request creation so it does not attach a JSON body: when calling http.NewRequest for the GET call (the line creating req in the current code) pass nil as the body instead of bytes.NewBuffer(jsonData); remove or conditionally create jsonData only for non-GET methods (or reuse the existing JSON body logic only for POST/PUT), ensuring the request creation in the function that builds the HTTP call uses http.NewRequest("GET", url, nil) for GET requests.
405-417: Reusing DeepSeek'sDSModelList/DSModeltypes creates cross-provider coupling.Parsing SiliconFlow's
/modelsresponse viaDSModelList/DSModel(defined for DeepSeek) couples the two drivers: a schema tweak in DeepSeek's types silently changes SiliconFlow behavior. Since both appear to be OpenAI-compatible{data: [{id, owned_by}, ...]}, consider extracting a sharedOpenAIModelListtype in a common file (or package-level) and using it from both drivers.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/entity/models/siliconflow.go` around lines 405 - 417, The current SiliconFlow parsing uses DeepSeek types DSModelList/DSModel which couples providers; replace those usages by introducing a shared OpenAI-compatible struct (e.g., OpenAIModelList with Data items containing ID and OwnedBy) in a common package and update the SiliconFlow code that unmarshals into DSModelList and iterates over modelList.Models to instead unmarshal into and iterate over OpenAIModelList.Data, constructing modelName the same way; keep DeepSeek using its own types or migrate both callers to the shared OpenAIModelList to avoid cross-provider coupling.internal/cli/user_command.go (1)
1504-1536: Localthinkingflag is overloaded for SSE print state.
thinkingis received as an input (line 1480) indicating whether the caller requested a thinking response, then reassigned at Line 1517 to drive the "print a newline beforeAnswer:" decision. It works, but mixing the input intent with display state is easy to break later. Consider introducing a separatereasoningEmittedbool for the SSE loop to keep the original flag immutable.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/cli/user_command.go` around lines 1504 - 1536, The SSE loop currently mutates the input flag thinking to track whether a "[REASONING]" chunk has been emitted; introduce a new local bool (e.g., reasoningEmitted) and use it for the loop's print state instead of reassigning thinking: when you first print "Thinking: " set reasoningEmitted = true (leave thinking unchanged), and when deciding whether to print a newline before "Answer:" use reasoningEmitted rather than thinking; update references in the blocks handling "[REASONING]" and "[MESSAGE]" to rely on reasoningEmitted while keeping reasoningPrint and messagePrint logic intact.internal/cli/user_parser.go (1)
2243-2250: Stale comment and misleading variable name after/→@switch.The comment still says "contains two slashes" / "contains exactly 2 slashes" and the variable is
slashCount, yet the code counts@. Consider renaming for clarity.Proposed fix
- // Check if we have a quoted string that looks like a model identifier (contains two slashes) + // Check if we have a quoted string that looks like a model identifier (contains two '@') // Format: 'model@instance@provider' or just 'message' if p.curToken.Type == TokenQuotedString { firstArg := p.curToken.Value - // Check if it looks like a model identifier (contains exactly 2 slashes) - slashCount := strings.Count(firstArg, "@") - if slashCount == 2 { + // Check if it looks like a model identifier (contains exactly 2 '@') + atCount := strings.Count(firstArg, "@") + if atCount == 2 {🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/cli/user_parser.go` around lines 2243 - 2250, Comment and variable name are stale: the code in the TokenQuotedString branch counts '@' but comments and the variable name refer to slashes and "slashCount". Update the comment to say "contains two @ characters" or "contains exactly 2 '@' separators" and rename the variable `slashCount` to something like `atCount` or `providerSepCount`; keep the logic that checks strings.Count(firstArg, "@") == 2 and ensure references to `slashCount` are replaced with the new name (symbols: p.curToken, TokenQuotedString, firstArg, slashCount -> atCount/providerSepCount).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@conf/models/siliconflow.json`:
- Around line 35-42: The "thinking" feature block currently lists a
non-SiliconFlow model ("deepseek-chat") causing the feature to be advertised but
never matched; update the "features"."thinking"."supported_models" array to
include actual SiliconFlow models (e.g., Qwen3-series names used elsewhere in
this file such as entries under the provider like "qwen3" / "qwen3-mini" /
"qwen3-large" or other qwen/* identifiers), or remove the entire "thinking"
feature block if no SiliconFlow model supports it; ensure "default_value"
remains consistent with the presence or absence of valid entries so the feature
is not advertised incorrectly.
- Around line 6-11: The URL suffix config is missing the async_chat key which
causes SiliconflowModel.Chat to branch to z.URLSuffix.AsyncChat (see
siliconflow.go:76) and produce a malformed URL; add an "async_chat" entry under
"url_suffix" with the correct async path used by the SiliconFlow API (or remove
the async branch if the driver shouldn't support async). Also fix the thinking
feature's supported_models list by removing non-SiliconFlow entries like
"deepseek-chat" and either replace them with the actual SiliconFlow model names
that support thinking or remove the thinking feature entirely; update the
thinking supported_models field accordingly so it accurately reflects
driver-supported models.
In `@internal/entity/models/siliconflow.go`:
- Around line 186-202: The streaming implementation in
SiliconflowModel.ChatStreamlyWithSender hardcodes "/chat/completions", doesn't
honor z.URLSuffix.Chat/AsyncChat and sets "stream": false; update
ChatStreamlyWithSender to build url using z.BaseURL[region] + the appropriate
suffix (use z.URLSuffix.AsyncChat for qwen/glm-like models the same way the
non-streaming Chat method does, otherwise z.URLSuffix.Chat), ensure the request
body sets "stream": true, and keep the same model detection logic as Chat so
streaming and non-streaming use consistent endpoints and behavior.
- Line 175: Guard against a nil ModelSeries before calling GetThinkingAndAnswer:
in the code path that calls GetThinkingAndAnswer(chatModelConfig.ModelSeries,
&content) check if chatModelConfig.ModelSeries == nil and either (a) populate a
sensible default model series (or convert to the helper's expected non-nil
value) and call GetThinkingAndAnswer, or (b) skip the call and set safe default
values for thinking and answer / return an error; alternatively make
GetThinkingAndAnswer nil-safe by handling a nil modelSeries inside that function
(switch on a safe default) — reference chatModelConfig.ModelSeries and
GetThinkingAndAnswer to locate where to add the nil-check or the helper change.
- Around line 264-349: The loop currently accumulates all deltas into
reserveText until a <think> block flips thinkingPhase/answerPhase, which
prevents streaming when no <think> tags are emitted; modify the SSE handling
around delta/content (variables: delta, content, reserveText, thinkingPhase,
answerPhase) so that when content arrives and neither thinkingPhase nor
answerPhase is true you implicitly enter answerPhase (set answerPhase = true)
and forward the content immediately via sender(&content, nil) instead of
appending to reserveText; keep the existing trimming behavior, preserve the
handling for explicit <think> / </think> transitions, and ensure the final
reserveText flush remains for any leftover buffered text.
- Around line 70-77: The model-series detection in siliconflow.go incorrectly
compares the whole provider-prefixed modelName and fails to match variants like
"qwen3" or "qwen3.5"; replace the current modelSeries logic by first stripping
any provider prefix (split on "/" and take the last segment), then extract the
name prefix (split on "-" and take [0]) and use prefix checks
(strings.HasPrefix) for "qwen" or "glm" (e.g., if strings.HasPrefix(series,
"qwen") || strings.HasPrefix(series, "glm") then set url = z.BaseURL[region] +
z.URLSuffix.AsyncChat). Update the code around modelSeries and the conditional
that sets URLSuffix.AsyncChat to use this new series detection (referencing
modelName, modelSeries, and z.URLSuffix.AsyncChat).
---
Outside diff comments:
In `@internal/cli/user_parser.go`:
- Around line 1671-1674: Update the comment and error message that describe the
expected composite model name format in the parsing branch that checks
p.curToken.Type (the branch returning fmt.Errorf("expected quoted string with
format provider/instance/model")); change the wording to match the new canonical
format used elsewhere ("model@instance@provider") so the parser, its comment,
and the error string all refer to composite_model_name using '@' rather than
'/'. Locate the branch in user_parser.go where p.curToken.Type !=
TokenQuotedString is checked and replace the legacy description with the new '@'
format for consistency with CHAT and USE MODEL.
In `@internal/handler/providers.go`:
- Around line 618-626: The debug uses Go's builtin println which doesn't format
verbs and leaks a stray debug print; in both EnableOrDisableModel and
ChatToModel replace the println("JSON bind error: %v (type: %T)", err, err) with
the project's logger (e.g., processLogger.Errorf or the handler's logger) and
log the formatted error and type, then keep the existing c.JSON BadRequest
response path; remove the println calls entirely so only the structured logger
reports the binding error for c.ShouldBindJSON in those handlers.
- Around line 684-736: The stream path fails to set modelConfig.ModelSeries
causing potential nil deref in GetThinkingAndAnswer; update
ChatToModelStreamWithSender to mirror ChatToModel by assigning
modelConfig.ModelSeries = model.Series (using the same model lookup used in the
non-streaming path) before calling
ChatStreamlyWithSender/ChatToModelStreamWithSender, or alternatively add a
nil-check in GetThinkingAndAnswer for *modelSeries; prefer the first fix to keep
behavior symmetric across ChatToModel and ChatToModelStreamWithSender and
reference the symbols: ChatToModelStreamWithSender, ChatToModel,
modelConfig.ModelSeries, ChatStreamlyWithSender, and GetThinkingAndAnswer.
---
Nitpick comments:
In `@internal/cli/user_command.go`:
- Around line 1504-1536: The SSE loop currently mutates the input flag thinking
to track whether a "[REASONING]" chunk has been emitted; introduce a new local
bool (e.g., reasoningEmitted) and use it for the loop's print state instead of
reassigning thinking: when you first print "Thinking: " set reasoningEmitted =
true (leave thinking unchanged), and when deciding whether to print a newline
before "Answer:" use reasoningEmitted rather than thinking; update references in
the blocks handling "[REASONING]" and "[MESSAGE]" to rely on reasoningEmitted
while keeping reasoningPrint and messagePrint logic intact.
In `@internal/cli/user_parser.go`:
- Around line 2243-2250: Comment and variable name are stale: the code in the
TokenQuotedString branch counts '@' but comments and the variable name refer to
slashes and "slashCount". Update the comment to say "contains two @ characters"
or "contains exactly 2 '@' separators" and rename the variable `slashCount` to
something like `atCount` or `providerSepCount`; keep the logic that checks
strings.Count(firstArg, "@") == 2 and ensure references to `slashCount` are
replaced with the new name (symbols: p.curToken, TokenQuotedString, firstArg,
slashCount -> atCount/providerSepCount).
In `@internal/entity/models/siliconflow.go`:
- Around line 381-384: In siliconflow.go change the GET request creation so it
does not attach a JSON body: when calling http.NewRequest for the GET call (the
line creating req in the current code) pass nil as the body instead of
bytes.NewBuffer(jsonData); remove or conditionally create jsonData only for
non-GET methods (or reuse the existing JSON body logic only for POST/PUT),
ensuring the request creation in the function that builds the HTTP call uses
http.NewRequest("GET", url, nil) for GET requests.
- Around line 405-417: The current SiliconFlow parsing uses DeepSeek types
DSModelList/DSModel which couples providers; replace those usages by introducing
a shared OpenAI-compatible struct (e.g., OpenAIModelList with Data items
containing ID and OwnedBy) in a common package and update the SiliconFlow code
that unmarshals into DSModelList and iterates over modelList.Models to instead
unmarshal into and iterate over OpenAIModelList.Data, constructing modelName the
same way; keep DeepSeek using its own types or migrate both callers to the
shared OpenAIModelList to avoid cross-provider coupling.
🪄 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: 84ffea57-36a0-4fc8-ada6-a3f38e8be413
📒 Files selected for processing (9)
conf/models/deepseek.jsonconf/models/moonshot.jsonconf/models/siliconflow.jsoninternal/cli/user_command.gointernal/cli/user_parser.gointernal/entity/models/factory.gointernal/entity/models/siliconflow.gointernal/handler/providers.gointernal/router/router.go
🚧 Files skipped from review as they are similar to previous changes (3)
- internal/entity/models/factory.go
- conf/models/moonshot.json
- conf/models/deepseek.json
| "url_suffix": { | ||
| "chat": "chat/completions", | ||
| "models": "models", | ||
| "embeddings": "embeddings", | ||
| "rerank": "rerank" | ||
| }, |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Verify whether URLSuffix has an AsyncChat field and how it's loaded.
rg -nP --type=go -C3 '\bAsyncChat\b'
fd -e json . conf/models | xargs -I{} sh -c 'echo "=== {} ==="; cat {}'Repository: infiniflow/ragflow
Length of output: 15899
Missing async_chat suffix and incorrect thinking feature configuration.
SiliconflowModel.Chat branches to z.URLSuffix.AsyncChat when the model prefix is qwen or glm (siliconflow.go:76), but this config only defines chat, models, embeddings, and rerank. When AsyncChat is unmarshalled as empty, the async path will produce a malformed URL (<base>/).
Additionally, the thinking feature lists deepseek-chat as a supported model, which is a DeepSeek provider model, not a SiliconFlow model. Either add the actual SiliconFlow model names that support thinking or remove the feature if none of these models support it.
Fix: Add "async_chat" to url_suffix (or remove the async branch from the driver if not supported), and correct the thinking supported_models list.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@conf/models/siliconflow.json` around lines 6 - 11, The URL suffix config is
missing the async_chat key which causes SiliconflowModel.Chat to branch to
z.URLSuffix.AsyncChat (see siliconflow.go:76) and produce a malformed URL; add
an "async_chat" entry under "url_suffix" with the correct async path used by the
SiliconFlow API (or remove the async branch if the driver shouldn't support
async). Also fix the thinking feature's supported_models list by removing
non-SiliconFlow entries like "deepseek-chat" and either replace them with the
actual SiliconFlow model names that support thinking or remove the thinking
feature entirely; update the thinking supported_models field accordingly so it
accurately reflects driver-supported models.
| "features": { | ||
| "thinking": { | ||
| "default_value": true, | ||
| "supported_models": [ | ||
| "deepseek-chat" | ||
| ] | ||
| } | ||
| } |
There was a problem hiding this comment.
supported_models for thinking references a model that isn't in this provider.
deepseek-chat is a DeepSeek model, not one of SiliconFlow's qwen/* or tencent/* entries above. Combined with default_value: true, the thinking feature will be advertised but never match any listed model. This looks like a copy/paste from deepseek.json; please update it to reference SiliconFlow's actual thinking-capable models (e.g. the Qwen3 series) or remove the block.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@conf/models/siliconflow.json` around lines 35 - 42, The "thinking" feature
block currently lists a non-SiliconFlow model ("deepseek-chat") causing the
feature to be advertised but never matched; update the
"features"."thinking"."supported_models" array to include actual SiliconFlow
models (e.g., Qwen3-series names used elsewhere in this file such as entries
under the provider like "qwen3" / "qwen3-mini" / "qwen3-large" or other qwen/*
identifiers), or remove the entire "thinking" feature block if no SiliconFlow
model supports it; ensure "default_value" remains consistent with the presence
or absence of valid entries so the feature is not advertised incorrectly.
| url := fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.Chat) | ||
|
|
||
| // I need to get the model series, such as qwen3 is the prefix, the model series will be qwen. glm is the prefix, the model series will be glm. such as the model name: qwen3-0.6b, the model series will be qwen3 | ||
| // the model name is glm-4.7, the model series will be glm | ||
| modelSeries := strings.Split(*modelName, "-")[0] | ||
| if modelSeries == "qwen" || modelSeries == "glm" { | ||
| url = fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.AsyncChat) | ||
| } |
There was a problem hiding this comment.
Model-series detection doesn't match actual configured model names.
conf/models/siliconflow.json registers models as qwen/qwen3-8b, qwen/qwen3.5-4b, tencent/hunyuan-mt-7b. With strings.Split(*modelName, "-")[0] you get qwen/qwen3, qwen/qwen3.5, tencent/hunyuan — none equal "qwen" or "glm". Even by the author's own comment (qwen3-0.6b → qwen3), the equality modelSeries == "qwen" fails on qwen3. Net effect: the async-chat branch is effectively dead.
Switch to a prefix/contains check (and handle the provider-prefixed form):
Proposed fix
- modelSeries := strings.Split(*modelName, "-")[0]
- if modelSeries == "qwen" || modelSeries == "glm" {
+ // Strip the provider prefix (e.g. "qwen/qwen3-8b" -> "qwen3-8b") before extracting the family.
+ shortName := *modelName
+ if idx := strings.LastIndex(shortName, "/"); idx >= 0 {
+ shortName = shortName[idx+1:]
+ }
+ if strings.HasPrefix(shortName, "qwen") || strings.HasPrefix(shortName, "glm") {
url = fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.AsyncChat)
}📝 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.
| url := fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.Chat) | |
| // I need to get the model series, such as qwen3 is the prefix, the model series will be qwen. glm is the prefix, the model series will be glm. such as the model name: qwen3-0.6b, the model series will be qwen3 | |
| // the model name is glm-4.7, the model series will be glm | |
| modelSeries := strings.Split(*modelName, "-")[0] | |
| if modelSeries == "qwen" || modelSeries == "glm" { | |
| url = fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.AsyncChat) | |
| } | |
| url := fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.Chat) | |
| // I need to get the model series, such as qwen3 is the prefix, the model series will be qwen. glm is the prefix, the model series will be glm. such as the model name: qwen3-0.6b, the model series will be qwen3 | |
| // the model name is glm-4.7, the model series will be glm | |
| // Strip the provider prefix (e.g. "qwen/qwen3-8b" -> "qwen3-8b") before extracting the family. | |
| shortName := *modelName | |
| if idx := strings.LastIndex(shortName, "/"); idx >= 0 { | |
| shortName = shortName[idx+1:] | |
| } | |
| if strings.HasPrefix(shortName, "qwen") || strings.HasPrefix(shortName, "glm") { | |
| url = fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.AsyncChat) | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/models/siliconflow.go` around lines 70 - 77, The model-series
detection in siliconflow.go incorrectly compares the whole provider-prefixed
modelName and fails to match variants like "qwen3" or "qwen3.5"; replace the
current modelSeries logic by first stripping any provider prefix (split on "/"
and take the last segment), then extract the name prefix (split on "-" and take
[0]) and use prefix checks (strings.HasPrefix) for "qwen" or "glm" (e.g., if
strings.HasPrefix(series, "qwen") || strings.HasPrefix(series, "glm") then set
url = z.BaseURL[region] + z.URLSuffix.AsyncChat). Update the code around
modelSeries and the conditional that sets URLSuffix.AsyncChat to use this new
series detection (referencing modelName, modelSeries, and
z.URLSuffix.AsyncChat).
| return nil, fmt.Errorf("invalid content format") | ||
| } | ||
|
|
||
| thinking, answer := GetThinkingAndAnswer(chatModelConfig.ModelSeries, &content) |
There was a problem hiding this comment.
Potential nil-pointer deref on chatModelConfig.ModelSeries.
GetThinkingAndAnswer (per internal/entity/models/common.go:21-27) does switch *modelSeries — if ModelSeries is ever nil (e.g. the model row's Series column is empty, or a future call site forgets to set it), this panics. Either guard here or make the helper nil-safe.
Suggested guard
- thinking, answer := GetThinkingAndAnswer(chatModelConfig.ModelSeries, &content)
+ var thinking, answer *string
+ if chatModelConfig.ModelSeries != nil {
+ thinking, answer = GetThinkingAndAnswer(chatModelConfig.ModelSeries, &content)
+ } else {
+ answer = &content
+ }📝 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.
| thinking, answer := GetThinkingAndAnswer(chatModelConfig.ModelSeries, &content) | |
| var thinking, answer *string | |
| if chatModelConfig.ModelSeries != nil { | |
| thinking, answer = GetThinkingAndAnswer(chatModelConfig.ModelSeries, &content) | |
| } else { | |
| answer = &content | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/models/siliconflow.go` at line 175, Guard against a nil
ModelSeries before calling GetThinkingAndAnswer: in the code path that calls
GetThinkingAndAnswer(chatModelConfig.ModelSeries, &content) check if
chatModelConfig.ModelSeries == nil and either (a) populate a sensible default
model series (or convert to the helper's expected non-nil value) and call
GetThinkingAndAnswer, or (b) skip the call and set safe default values for
thinking and answer / return an error; alternatively make GetThinkingAndAnswer
nil-safe by handling a nil modelSeries inside that function (switch on a safe
default) — reference chatModelConfig.ModelSeries and GetThinkingAndAnswer to
locate where to add the nil-check or the helper change.
| func (z *SiliconflowModel) ChatStreamlyWithSender(modelName, message *string, apiConfig *APIConfig, chatModelConfig *ChatConfig, sender func(*string, *string) error) error { | ||
| var region = "default" | ||
| if apiConfig.Region != nil { | ||
| region = *apiConfig.Region | ||
| } | ||
|
|
||
| url := fmt.Sprintf("%s/chat/completions", z.BaseURL[region]) | ||
|
|
||
| // Build request body with streaming enabled | ||
| reqBody := map[string]interface{}{ | ||
| "model": modelName, | ||
| "messages": []map[string]string{ | ||
| {"role": "user", "content": *message}, | ||
| }, | ||
| "stream": false, | ||
| "temperature": 1, | ||
| } |
There was a problem hiding this comment.
Streaming path hardcodes /chat/completions and skips the async-chat branch.
Two problems here:
- Line 192 ignores
z.URLSuffix.Chat(which is what the non-streamingChatuses) — if the config's URL suffix ever changes, streaming will silently 404. - Unlike
Chat(lines 74–77), streaming never switches toAsyncChatfor qwen/glm models, so behavior diverges between streaming and non-streaming for the same model. - Line 200 still defaults
"stream": falsein a function whose entire purpose is streaming; it's rescued by the handler settingStream=true, but a caller that forgets to set it would hit a non-streaming response and cause the SSE parser below to misbehave.
Proposed fix
- url := fmt.Sprintf("%s/chat/completions", z.BaseURL[region])
+ url := fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.Chat)
+ shortName := *modelName
+ if idx := strings.LastIndex(shortName, "/"); idx >= 0 {
+ shortName = shortName[idx+1:]
+ }
+ if strings.HasPrefix(shortName, "qwen") || strings.HasPrefix(shortName, "glm") {
+ url = fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.AsyncChat)
+ }
// Build request body with streaming enabled
reqBody := map[string]interface{}{
"model": modelName,
"messages": []map[string]string{
{"role": "user", "content": *message},
},
- "stream": false,
+ "stream": true,
"temperature": 1,
}🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/models/siliconflow.go` around lines 186 - 202, The streaming
implementation in SiliconflowModel.ChatStreamlyWithSender hardcodes
"/chat/completions", doesn't honor z.URLSuffix.Chat/AsyncChat and sets "stream":
false; update ChatStreamlyWithSender to build url using z.BaseURL[region] + the
appropriate suffix (use z.URLSuffix.AsyncChat for qwen/glm-like models the same
way the non-streaming Chat method does, otherwise z.URLSuffix.Chat), ensure the
request body sets "stream": true, and keep the same model detection logic as
Chat so streaming and non-streaming use consistent endpoints and behavior.
| reserveText := "" | ||
| thinkingPhase := false | ||
| answerPhase := false | ||
|
|
||
| // SSE parsing: read line by line | ||
| scanner := bufio.NewScanner(resp.Body) | ||
| for scanner.Scan() { | ||
| line := scanner.Text() | ||
| logger.Info(line) | ||
|
|
||
| // SSE data line starts with "data:" | ||
| if !strings.HasPrefix(line, "data:") { | ||
| continue | ||
| } | ||
|
|
||
| // Extract JSON after "data:" | ||
| data := strings.TrimSpace(line[5:]) | ||
|
|
||
| // [DONE] marks the end of stream | ||
| if data == "[DONE]" { | ||
| break | ||
| } | ||
|
|
||
| // Parse the JSON event | ||
| var event map[string]interface{} | ||
| if err = json.Unmarshal([]byte(data), &event); err != nil { | ||
| continue | ||
| } | ||
|
|
||
| choices, ok := event["choices"].([]interface{}) | ||
| if !ok || len(choices) == 0 { | ||
| continue | ||
| } | ||
|
|
||
| firstChoice, ok := choices[0].(map[string]interface{}) | ||
| if !ok { | ||
| continue | ||
| } | ||
|
|
||
| delta, ok := firstChoice["delta"].(map[string]interface{}) | ||
| if !ok { | ||
| continue | ||
| } | ||
|
|
||
| content, ok := delta["content"].(string) | ||
| if ok && content != "" { | ||
| if content == "<think>" { | ||
| thinkingPhase = true | ||
| continue | ||
|
|
||
| } else if content == "</think>" { | ||
| thinkingPhase = false | ||
| answerPhase = true | ||
| continue | ||
| } | ||
|
|
||
| if thinkingPhase { | ||
| if err = sender(nil, &content); err != nil { | ||
| return err | ||
| } | ||
| reserveText = "" | ||
| } else if answerPhase { | ||
| if err = sender(&content, nil); err != nil { | ||
| return err | ||
| } | ||
| reserveText = "" | ||
| } else { | ||
| content = strings.Trim(content, "\n") | ||
| content = strings.Trim(content, " ") | ||
| if content != "" { | ||
| reserveText += content | ||
| } | ||
| } | ||
| } | ||
|
|
||
| finishReason, ok := firstChoice["finish_reason"].(string) | ||
| if ok && finishReason != "" { | ||
| break | ||
| } | ||
| } | ||
|
|
||
| if reserveText != "" { | ||
| if err = sender(&reserveText, nil); err != nil { | ||
| return err | ||
| } | ||
| } |
There was a problem hiding this comment.
reserveText defeats streaming for responses without <think> tags.
The SSE loop only forwards deltas to sender while thinkingPhase or answerPhase is true — both start false and only flip after explicit <think>/</think> frames. For a model that never emits a <think> block (e.g. thinking disabled, or a non-reasoning model), every delta accumulates into reserveText and is flushed once after line 345. The client effectively receives the full answer in one chunk at end-of-stream.
Suggested behavior: when neither phase has been entered and content arrives, treat it as answer (or enter answerPhase implicitly) and forward immediately.
Proposed fix
- } else {
- content = strings.Trim(content, "\n")
- content = strings.Trim(content, " ")
- if content != "" {
- reserveText += content
- }
- }
+ } else {
+ // No <think> markers — treat subsequent content as answer and stream immediately.
+ answerPhase = true
+ if err = sender(&content, nil); err != nil {
+ return err
+ }
+ }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/models/siliconflow.go` around lines 264 - 349, The loop
currently accumulates all deltas into reserveText until a <think> block flips
thinkingPhase/answerPhase, which prevents streaming when no <think> tags are
emitted; modify the SSE handling around delta/content (variables: delta,
content, reserveText, thinkingPhase, answerPhase) so that when content arrives
and neither thinkingPhase nor answerPhase is true you implicitly enter
answerPhase (set answerPhase = true) and forward the content immediately via
sender(&content, nil) instead of appending to reserveText; keep the existing
trimming behavior, preserve the handling for explicit <think> / </think>
transitions, and ensure the final reserveText flush remains for any leftover
buffered text.
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
### What problem does this PR solve? As title ### Type of change - [x] New Feature (non-breaking change which adds functionality) --------- Signed-off-by: Jin Hai <[email protected]>
What problem does this PR solve?
As title
Type of change