Repository navigation
Go: aliyun model provider - #14379
Conversation
Signed-off-by: Jin Hai <[email protected]>
📝 WalkthroughWalkthroughIntroduces Aliyun model driver with chat and streaming support, along with refactoring the model/provider discriminator field from Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant ModelService
participant AliyunDriver
participant AliyunAPI as Aliyun API
Client->>ModelService: ChatToModel(modelName, message)
ModelService->>AliyunDriver: Chat(modelName, message, apiConfig, chatConfig)
AliyunDriver->>AliyunDriver: Build JSON request<br/>(model, message, generation params)
AliyunDriver->>AliyunAPI: POST with Bearer auth
AliyunAPI-->>AliyunDriver: JSON response
AliyunDriver->>AliyunDriver: Extract content<br/>and reasoning_content
AliyunDriver-->>ModelService: ChatResponse
ModelService-->>Client: Result
Client->>ModelService: ChatToModel with streaming
ModelService->>AliyunDriver: ChatStreamlyWithSender()
AliyunDriver->>AliyunAPI: POST (stream=true)
AliyunAPI-->>AliyunDriver: SSE stream
AliyunDriver->>AliyunDriver: Parse SSE lines
loop For each data event
AliyunDriver->>AliyunDriver: Decode JSON chunk
AliyunDriver->>Client: sender(delta.content,<br/>delta.reasoning_content)
end
AliyunDriver->>Client: sender([DONE] marker)
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 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: 10
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/entity/models/common.go (1)
21-27:⚠️ Potential issue | 🔴 CriticalAdd a nil guard and consider broadening the match.
Two concerns:
*modelTypewill panic ifmodelTypeis nil. Several call paths now reach this fromchatModelConfig.ModelTypewhich is an optional*string.- The switch only matches the exact string
"qwen3". Combined with howmodel.Typeis derived inNewProviderManager(prefix split before-),qwen-*model families (e.g.qwen-flashfrom the newaliyun.json) silently skip thinking extraction because their derived type is"qwen", not"qwen3".🛠️ Suggested fix
-func GetThinkingAndAnswer(modelType *string, content *string) (*string, *string) { - switch *modelType { - case "qwen3": +func GetThinkingAndAnswer(modelType *string, content *string) (*string, *string) { + if modelType == nil { + return nil, content + } + switch *modelType { + case "qwen", "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 modelType without a nil check and only handles the exact "qwen3" value, causing panics and missed matches for qwen family models; add a nil guard for the modelType parameter (return nil, content if modelType == nil) and broaden the switch/match to accept the qwen family (e.g., treat values starting with "qwen" or include "qwen" alongside "qwen3") so extractThinkContent is invoked for qwen-* models; reference GetThinkingAndAnswer, modelType, content, extractThinkContent and consider how model.Type is derived in NewProviderManager/chatModelConfig.ModelType when implementing the guard and matching logic.
♻️ Duplicate comments (2)
internal/entity/models/gitee.go (2)
175-175:⚠️ Potential issue | 🟠 MajorSame nil-deref risk on
chatModelConfig.ModelTypeas insiliconflow.go.
GetThinkingAndAnswerdereferences the pointer unconditionally — please add a nil guard either at the callsite or inside the helper.🤖 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 nil-deref risk by ensuring chatModelConfig.ModelType is non-nil before calling GetThinkingAndAnswer (or modify GetThinkingAndAnswer to handle nil), e.g. check chatModelConfig != nil && chatModelConfig.ModelType != nil and provide a safe default or return early; update the call site around thinking, answer := GetThinkingAndAnswer(chatModelConfig.ModelType, &content) (and mirror the same guard pattern used/fixed in siliconflow.go) so the helper never receives a nil pointer.
72-77:⚠️ Potential issue | 🔴 CriticalSame routing bug as
siliconflow.go: qwen3 model names will not match.
strings.Split("qwen3-0.6b", "-")[0]is"qwen3", but the condition only accepts"qwen"/"glm", so qwen3 models never get routed toAsyncChat. See the detailed comment oninternal/entity/models/siliconflow.go(lines 72-77) for the proposed fix; please apply the same change here to keep the two providers in sync.🤖 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 in gitee.go uses exact equality on modelType derived from strings.Split(*modelName, "-")[0], so names like "qwen3-0.6b" yield "qwen3" and fail the equality check; change the condition to use prefix matching (e.g., strings.HasPrefix(modelType, "qwen") || strings.HasPrefix(modelType, "glm")) so models like "qwen3" and "glm-4.7" route to z.URLSuffix.AsyncChat (update the code around the modelType variable and the if that sets url using z.BaseURL[region] and z.URLSuffix.AsyncChat).
🧹 Nitpick comments (2)
internal/entity/models/gitee.go (1)
60-183: Large duplication withsiliconflow.go.The Chat (and ChatStreamlyWithSender) implementations in
gitee.goandsiliconflow.goare nearly identical, differing essentially only inName(). As more providers (now Aliyun) are added with the same OpenAI-compatible shape, consider extracting a common helper (e.g., anopenAICompatibleChat(modelName, message, apiConfig, chatModelConfig, baseURL, urlSuffix, name)function) to avoid drift like the prefix bug above silently propagating.🤖 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 - 183, GiteeModel.Chat (and its ChatStreamlyWithSender variant) is nearly identical to the implementation in siliconflow.go; extract a shared helper (e.g., openAICompatibleChat) that accepts modelName, message, apiConfig, chatModelConfig plus provider-specific parameters (baseURL map, URLSuffix struct and provider Name) and make GiteeModel.Chat and the siliconflow equivalents call that helper; ensure the helper contains the modelType prefix handling, request body build, HTTP request/response parsing, and GetThinkingAndAnswer call so future providers (Aliyun, etc.) reuse it and avoid duplicated logic/bugs.internal/entity/models/aliyun.go (1)
102-108: Simplify theThinkingboolean assignment.Same pattern is repeated in
ChatStreamlyWithSender(lines 234-240). The if/else can be collapsed to a direct dereference.♻️ Proposed refactor
if chatModelConfig.Thinking != nil { - if *chatModelConfig.Thinking { - reqBody["enable_thinking"] = true - } else { - reqBody["enable_thinking"] = false - } + reqBody["enable_thinking"] = *chatModelConfig.Thinking }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/entity/models/aliyun.go` around lines 102 - 108, The verbose if/else that sets reqBody["enable_thinking"] should be collapsed to a direct dereference: when chatModelConfig.Thinking != nil assign reqBody["enable_thinking"] = *chatModelConfig.Thinking; apply the same simplification in the ChatStreamlyWithSender block (the code around the existing Thinking nil-check at lines referenced in the review) so both places keep the nil check but use the direct assignment instead of the if/else branches.
🤖 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/aliyun.json`:
- Line 13: The JSON has a stale "series" key so Provider.Type remains empty;
update the provider JSON to use the "type" key (e.g., "type": "deepseek") and,
after you fix the related bug in internal/entity/model.go (the suspicious
assignment model.Type = &provider.Name), ensure NewProviderManager receives the
correct provider.Type so its prefix-derivation branch is not triggered; also
verify GetThinkingAndAnswer now sees the intended "deepseek" type (or the
correct type string) so thinking extraction runs when the thinking feature is
enabled.
In `@internal/entity/model.go`:
- Around line 261-262: Guard against strings.Index returning -1 before slicing
model.Name: check the computed pos and if pos == -1 (no "-" present) set
modelType to a safe fallback (e.g., the full model.Name or a default string) or
handle the error path instead of slicing; update the code around the variables
pos and modelType where model.Name is parsed so you no longer do
model.Name[0:pos] when pos is -1.
- Around line 260-266: The model discriminator is being set to the provider name
instead of its configured type: in the else branch change the assignment to use
provider.Type (i.e., set model.Type to &provider.Type, not &provider.Name) so
model.Type contains values like "qwen3"/"glm"/"deepseek" expected by
GetThinkingAndAnswer and the AsyncChat routing in siliconflow.go/gitee.go; after
code change, update conf/models/*.json to replace any stale "series" keys with
"type" values that match provider.Type.
In `@internal/entity/models/aliyun.go`:
- Around line 55-57: The AliyunModel.Name() method currently returns the wrong
provider string; update the Name() implementation on the AliyunModel type to
return "aliyun" (replace the incorrect "siliconflow" value) so name-based
lookups and error messages correctly attribute to Aliyun; locate the method by
the symbol AliyunModel.Name and change the returned literal to "aliyun", then
run relevant unit/integration tests that exercise ChatWithMessages,
EncodeToEmbedding and Balance to confirm correct behavior.
- Around line 200-212: The request body in ChatStreamlyWithSender incorrectly
sets "stream" to false by default which breaks the SSE flow; change the logic in
the request body construction so that "stream" defaults to true when
chatModelConfig.Stream is nil and only uses chatModelConfig.Stream's value when
it is non-nil (i.e., set reqBody["stream"] = true initially and then if
chatModelConfig.Stream != nil override it with *chatModelConfig.Stream),
ensuring the streaming endpoint receives stream=true by default and preserving
explicit false when caller sets it.
- Around line 164-174: The code currently returns an error when
chatModelConfig.Thinking is true but messageMap["reasoning_content"] is missing
or not a string; instead, in the block that checks chatModelConfig.Thinking,
detect whether messageMap["reasoning_content"] exists and is a string and only
assign to reasonContent when it is, otherwise set reasonContent = "" (or leave
nil/empty) and continue without returning an error; also remove or change the
misleading "invalid content format" error to avoid failing valid completions
(refer to chatModelConfig.Thinking, reasonContent, and messageMap in
internal/entity/models/aliyun.go).
- Around line 267-270: The current use of bufio.NewScanner with its default 64KB
token and the per-line logger.Info are unsafe for SSE: increase the scanner's
buffer by calling scanner.Buffer(...) after bufio.NewScanner to a much larger
max token (e.g., multiple MBs) and handle scanner.Err() after the loop to
surface errors, and change logger.Info(line) to logger.Debug(line) or remove the
per-chunk log to avoid logging full model outputs/PII; update references around
bufio.NewScanner, scanner.Scan(), and logger.Info to implement these changes.
- Around line 365-378: In ListModels: stop sending an empty JSON body with the
GET by passing nil as the body to http.NewRequest instead of
bytes.NewBuffer(jsonData) and remove the json.Marshal of an empty map; also add
a nil-check for apiConfig.ApiKey before dereferencing (guard *apiConfig.ApiKey
or use a safe local variable) and only set the Authorization header using that
validated value (adjust the req.Header.Set calls around req and apiConfig.ApiKey
accordingly).
In `@internal/entity/models/siliconflow.go`:
- Line 175: The call to GetThinkingAndAnswer(chatModelConfig.ModelType,
&content) can panic when chatModelConfig.ModelType is nil because
GetThinkingAndAnswer dereferences the pointer; before calling, ensure
chatModelConfig.ModelType is non-nil by providing a sensible default (e.g., set
to a default model string) or perform a nil-check and branch to a fallback path;
alternatively update GetThinkingAndAnswer to accept a nil *string and handle it
safely (nil-check inside GetThinkingAndAnswer). Reference symbols: adjust the
caller in siliconflow.go where GetThinkingAndAnswer(...) is invoked or modify
GetThinkingAndAnswer in internal/entity/models/common.go to guard against nil.
- Around line 72-77: The routing condition misidentifies qwen3 models because
modelType equals "qwen3" not "qwen"; update the condition in siliconflow.go to
use a prefix check (e.g., strings.HasPrefix(modelType, "qwen")) instead of
strict equality so qwen3, qwen2, etc. match, keep the glm equality as-is, and
update the comment to reflect that qwen* model types (like qwen3) should route
to z.URLSuffix.AsyncChat using z.BaseURL[region].
---
Outside diff comments:
In `@internal/entity/models/common.go`:
- Around line 21-27: GetThinkingAndAnswer currently dereferences modelType
without a nil check and only handles the exact "qwen3" value, causing panics and
missed matches for qwen family models; add a nil guard for the modelType
parameter (return nil, content if modelType == nil) and broaden the switch/match
to accept the qwen family (e.g., treat values starting with "qwen" or include
"qwen" alongside "qwen3") so extractThinkContent is invoked for qwen-* models;
reference GetThinkingAndAnswer, modelType, content, extractThinkContent and
consider how model.Type is derived in
NewProviderManager/chatModelConfig.ModelType when implementing the guard and
matching logic.
---
Duplicate comments:
In `@internal/entity/models/gitee.go`:
- Line 175: Get rid of the nil-deref risk by ensuring chatModelConfig.ModelType
is non-nil before calling GetThinkingAndAnswer (or modify GetThinkingAndAnswer
to handle nil), e.g. check chatModelConfig != nil && chatModelConfig.ModelType
!= nil and provide a safe default or return early; update the call site around
thinking, answer := GetThinkingAndAnswer(chatModelConfig.ModelType, &content)
(and mirror the same guard pattern used/fixed in siliconflow.go) so the helper
never receives a nil pointer.
- Around line 72-77: The routing check in gitee.go uses exact equality on
modelType derived from strings.Split(*modelName, "-")[0], so names like
"qwen3-0.6b" yield "qwen3" and fail the equality check; change the condition to
use prefix matching (e.g., strings.HasPrefix(modelType, "qwen") ||
strings.HasPrefix(modelType, "glm")) so models like "qwen3" and "glm-4.7" route
to z.URLSuffix.AsyncChat (update the code around the modelType variable and the
if that sets url using z.BaseURL[region] and z.URLSuffix.AsyncChat).
---
Nitpick comments:
In `@internal/entity/models/aliyun.go`:
- Around line 102-108: The verbose if/else that sets reqBody["enable_thinking"]
should be collapsed to a direct dereference: when chatModelConfig.Thinking !=
nil assign reqBody["enable_thinking"] = *chatModelConfig.Thinking; apply the
same simplification in the ChatStreamlyWithSender block (the code around the
existing Thinking nil-check at lines referenced in the review) so both places
keep the nil check but use the direct assignment instead of the if/else
branches.
In `@internal/entity/models/gitee.go`:
- Around line 60-183: GiteeModel.Chat (and its ChatStreamlyWithSender variant)
is nearly identical to the implementation in siliconflow.go; extract a shared
helper (e.g., openAICompatibleChat) that accepts modelName, message, apiConfig,
chatModelConfig plus provider-specific parameters (baseURL map, URLSuffix struct
and provider Name) and make GiteeModel.Chat and the siliconflow equivalents call
that helper; ensure the helper contains the modelType prefix handling, request
body build, HTTP request/response parsing, and GetThinkingAndAnswer call so
future providers (Aliyun, etc.) reuse it and avoid duplicated logic/bugs.
🪄 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: 98d350a4-96ad-43d0-81bf-0f68ab267b57
📒 Files selected for processing (9)
conf/models/aliyun.jsoninternal/entity/model.gointernal/entity/models/aliyun.gointernal/entity/models/common.gointernal/entity/models/factory.gointernal/entity/models/gitee.gointernal/entity/models/siliconflow.gointernal/entity/models/types.gointernal/service/model_service.go
| "embedding": "compatible-mode/v1/embeddings", | ||
| "models": "api/v1/deployments/models" | ||
| }, | ||
| "series": "deepseek", |
There was a problem hiding this comment.
Stale "series" key — not parsed after the rename.
The Provider struct's JSON tag is now json:"type" (see internal/entity/model.go line 173), so "series": "deepseek" is silently ignored. As a result provider.Type ends up empty and the prefix-derivation branch in NewProviderManager runs, producing model.Type = "qwen" for qwen-flash. Since GetThinkingAndAnswer only switches on "qwen3", thinking extraction will never trigger for this provider despite the thinking feature being enabled below.
Also note: even renaming the key to "type": "deepseek" won't help, because of the suspicious model.Type = &provider.Name line in internal/entity/model.go (flagged separately) — please coordinate the fix with that one.
🛠️ Suggested change (after fixing model.go)
- "series": "deepseek",
+ "type": "qwen3",📝 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.
| "series": "deepseek", | |
| "type": "qwen3", |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@conf/models/aliyun.json` at line 13, The JSON has a stale "series" key so
Provider.Type remains empty; update the provider JSON to use the "type" key
(e.g., "type": "deepseek") and, after you fix the related bug in
internal/entity/model.go (the suspicious assignment model.Type =
&provider.Name), ensure NewProviderManager receives the correct provider.Type so
its prefix-derivation branch is not triggered; also verify GetThinkingAndAnswer
now sees the intended "deepseek" type (or the correct type string) so thinking
extraction runs when the thinking feature is enabled.
| if provider.Type == "" { | ||
| pos := strings.Index(model.Name, "-") | ||
| modelSeries := model.Name[0:pos] | ||
| model.Series = &modelSeries | ||
| modelType := model.Name[0:pos] | ||
| model.Type = &modelType | ||
| } else { | ||
| model.Series = &provider.Name | ||
| model.Type = &provider.Name | ||
| } |
There was a problem hiding this comment.
model.Type = &provider.Name is almost certainly wrong — should be &provider.Type.
In the else branch the model's discriminator is being assigned the provider's name (e.g., "Aliyun", "Gitee"), not the configured type. Downstream code (GetThinkingAndAnswer, the prefix-based AsyncChat routing in siliconflow.go/gitee.go) expects values like "qwen3", "glm", "deepseek" — not the provider name. This appears to be a leftover from the Series → Type rename (the previous code likely did &provider.Series).
This is the root cause that the stale "series" key in conf/models/aliyun.json was masking; please fix here and update the JSON in tandem.
🐛 Suggested fix
if provider.Type == "" {
pos := strings.Index(model.Name, "-")
+ if pos < 0 {
+ pos = len(model.Name)
+ }
modelType := model.Name[0:pos]
model.Type = &modelType
} else {
- model.Type = &provider.Name
+ model.Type = &provider.Type
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if provider.Type == "" { | |
| pos := strings.Index(model.Name, "-") | |
| modelSeries := model.Name[0:pos] | |
| model.Series = &modelSeries | |
| modelType := model.Name[0:pos] | |
| model.Type = &modelType | |
| } else { | |
| model.Series = &provider.Name | |
| model.Type = &provider.Name | |
| } | |
| if provider.Type == "" { | |
| pos := strings.Index(model.Name, "-") | |
| if pos < 0 { | |
| pos = len(model.Name) | |
| } | |
| modelType := model.Name[0:pos] | |
| model.Type = &modelType | |
| } else { | |
| model.Type = &provider.Type | |
| } |
🤖 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 model discriminator is
being set to the provider name instead of its configured type: in the else
branch change the assignment to use provider.Type (i.e., set model.Type to
&provider.Type, not &provider.Name) so model.Type contains values like
"qwen3"/"glm"/"deepseek" expected by GetThinkingAndAnswer and the AsyncChat
routing in siliconflow.go/gitee.go; after code change, update conf/models/*.json
to replace any stale "series" keys with "type" values that match provider.Type.
| pos := strings.Index(model.Name, "-") | ||
| modelSeries := model.Name[0:pos] | ||
| model.Series = &modelSeries | ||
| modelType := model.Name[0:pos] |
There was a problem hiding this comment.
Edge case: panic if model.Name contains no -.
strings.Index(model.Name, "-") returns -1 when the separator is missing, and model.Name[0:-1] will panic at runtime. Worth adding a small guard (or an explicit fallback) — see the suggested diff in the comment above.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/model.go` around lines 261 - 262, Guard against strings.Index
returning -1 before slicing model.Name: check the computed pos and if pos == -1
(no "-" present) set modelType to a safe fallback (e.g., the full model.Name or
a default string) or handle the error path instead of slicing; update the code
around the variables pos and modelType where model.Name is parsed so you no
longer do model.Name[0:pos] when pos is -1.
| func (z *AliyunModel) Name() string { | ||
| return "siliconflow" | ||
| } |
There was a problem hiding this comment.
Critical: Name() returns the wrong provider — "siliconflow" instead of "aliyun".
This looks like a copy-paste leftover. It will surface in every "not implemented" / error message produced by ChatWithMessages, EncodeToEmbedding, Balance, and any name-based lookup, misattributing failures to the SiliconFlow provider.
🐛 Proposed fix
func (z *AliyunModel) Name() string {
- return "siliconflow"
+ return "aliyun"
}📝 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 (z *AliyunModel) Name() string { | |
| return "siliconflow" | |
| } | |
| func (z *AliyunModel) Name() string { | |
| return "aliyun" | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/models/aliyun.go` around lines 55 - 57, The
AliyunModel.Name() method currently returns the wrong provider string; update
the Name() implementation on the AliyunModel type to return "aliyun" (replace
the incorrect "siliconflow" value) so name-based lookups and error messages
correctly attribute to Aliyun; locate the method by the symbol AliyunModel.Name
and change the returned literal to "aliyun", then run relevant unit/integration
tests that exercise ChatWithMessages, EncodeToEmbedding and Balance to confirm
correct behavior.
| var reasonContent string | ||
| if chatModelConfig.Thinking != nil && *chatModelConfig.Thinking { | ||
| reasonContent, ok = messageMap["reasoning_content"].(string) | ||
| if !ok { | ||
| return nil, fmt.Errorf("invalid content format") | ||
| } | ||
| // if first char of reasonContent is \n remove the '\n' | ||
| if reasonContent != "" && reasonContent[0] == '\n' { | ||
| reasonContent = reasonContent[1:] | ||
| } | ||
| } |
There was a problem hiding this comment.
Major: Don't fail the response when reasoning_content is missing/non-string.
When Thinking is enabled, the upstream API may still return a response without a reasoning_content field (e.g., the model produced no reasoning, or the field is null). Treating that as a hard error will reject otherwise valid completions and break end-user chat flows. The error message also misleadingly says "invalid content format".
🐛 Proposed fix
var reasonContent string
if chatModelConfig.Thinking != nil && *chatModelConfig.Thinking {
- reasonContent, ok = messageMap["reasoning_content"].(string)
- if !ok {
- return nil, fmt.Errorf("invalid content format")
- }
- // if first char of reasonContent is \n remove the '\n'
- if reasonContent != "" && reasonContent[0] == '\n' {
- reasonContent = reasonContent[1:]
- }
+ // reasoning_content may be absent or null even when thinking is enabled.
+ if rc, ok := messageMap["reasoning_content"].(string); ok {
+ reasonContent = strings.TrimPrefix(rc, "\n")
+ }
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| var reasonContent string | |
| if chatModelConfig.Thinking != nil && *chatModelConfig.Thinking { | |
| reasonContent, ok = messageMap["reasoning_content"].(string) | |
| if !ok { | |
| return nil, fmt.Errorf("invalid content format") | |
| } | |
| // if first char of reasonContent is \n remove the '\n' | |
| if reasonContent != "" && reasonContent[0] == '\n' { | |
| reasonContent = reasonContent[1:] | |
| } | |
| } | |
| var reasonContent string | |
| if chatModelConfig.Thinking != nil && *chatModelConfig.Thinking { | |
| // reasoning_content may be absent or null even when thinking is enabled. | |
| if rc, ok := messageMap["reasoning_content"].(string); ok { | |
| reasonContent = strings.TrimPrefix(rc, "\n") | |
| } | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/models/aliyun.go` around lines 164 - 174, The code currently
returns an error when chatModelConfig.Thinking is true but
messageMap["reasoning_content"] is missing or not a string; instead, in the
block that checks chatModelConfig.Thinking, detect whether
messageMap["reasoning_content"] exists and is a string and only assign to
reasonContent when it is, otherwise set reasonContent = "" (or leave nil/empty)
and continue without returning an error; also remove or change the misleading
"invalid content format" error to avoid failing valid completions (refer to
chatModelConfig.Thinking, reasonContent, and messageMap in
internal/entity/models/aliyun.go).
| // 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.
Critical: streaming endpoint defaults stream to false, breaking the entire SSE path.
ChatStreamlyWithSender hardcodes "stream": false and only overrides it when the caller explicitly sets chatModelConfig.Stream. If Stream is nil, the upstream returns a single non-SSE JSON body, the loop at line 273 drops every line (no data: prefix), and the function returns only the synthetic [DONE] marker — i.e., an empty stream. The comment on line 200 even says "with streaming enabled", which contradicts the value.
🐛 Proposed fix
// 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
- }(Inside the streaming method the caller's intent is unambiguous; honoring chatModelConfig.Stream=false here is nonsensical.)
📝 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.
| // 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 | |
| } | |
| // Build request body with streaming enabled | |
| reqBody := map[string]interface{}{ | |
| "model": modelName, | |
| "messages": []map[string]string{ | |
| {"role": "user", "content": *message}, | |
| }, | |
| "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/aliyun.go` around lines 200 - 212, The request body in
ChatStreamlyWithSender incorrectly sets "stream" to false by default which
breaks the SSE flow; change the logic in the request body construction so that
"stream" defaults to true when chatModelConfig.Stream is nil and only uses
chatModelConfig.Stream's value when it is non-nil (i.e., set reqBody["stream"] =
true initially and then if chatModelConfig.Stream != nil override it with
*chatModelConfig.Stream), ensuring the streaming endpoint receives stream=true
by default and preserving explicit false when caller sets it.
| scanner := bufio.NewScanner(resp.Body) | ||
| for scanner.Scan() { | ||
| line := scanner.Text() | ||
| logger.Info(line) |
There was a problem hiding this comment.
Major: bufio.Scanner default buffer (64KB) and per-line logger.Info are problematic for SSE.
bufio.NewScannerdefaults to a 64KB max token. Long SSE events — common withreasoning_contentpayloads from qwen models — will tripbufio.ErrTooLongand abort the stream mid-response. Set a larger buffer explicitly.logger.Info(line)logs every raw SSE chunk at INFO. That includes user prompts (echoed in some providers' first events) and the full model output, ballooning log volume and risking PII / sensitive content leakage into log aggregation systems. Drop it or downgrade to debug.
🛡️ Proposed fix
// SSE parsing: read line by line
scanner := bufio.NewScanner(resp.Body)
+ // SSE events with reasoning_content can exceed the default 64KB token size.
+ scanner.Buffer(make([]byte, 64*1024), 1024*1024)
for scanner.Scan() {
line := scanner.Text()
- logger.Info(line)📝 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.
| scanner := bufio.NewScanner(resp.Body) | |
| for scanner.Scan() { | |
| line := scanner.Text() | |
| logger.Info(line) | |
| // SSE parsing: read line by line | |
| scanner := bufio.NewScanner(resp.Body) | |
| // SSE events with reasoning_content can exceed the default 64KB token size. | |
| scanner.Buffer(make([]byte, 64*1024), 1024*1024) | |
| for scanner.Scan() { | |
| line := scanner.Text() |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/models/aliyun.go` around lines 267 - 270, The current use of
bufio.NewScanner with its default 64KB token and the per-line logger.Info are
unsafe for SSE: increase the scanner's buffer by calling scanner.Buffer(...)
after bufio.NewScanner to a much larger max token (e.g., multiple MBs) and
handle scanner.Err() after the loop to surface errors, and change
logger.Info(line) to logger.Debug(line) or remove the per-chunk log to avoid
logging full model outputs/PII; update references around bufio.NewScanner,
scanner.Scan(), and logger.Info to implement these changes.
| // 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)) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to create request: %w", err) | ||
| } | ||
|
|
||
| req.Header.Set("Content-Type", "application/json") |
There was a problem hiding this comment.
🧩 Analysis chain
🌐 Web query:
Aliyun DashScope models list endpoint HTTP method and URL
💡 Result:
No public HTTP API endpoint exists for listing Aliyun DashScope models. Official documentation directs users to the model list page at https://www.alibabacloud.com/help/zh/model-studio/getting-started/models or https://help.aliyun.com/zh/model-studio/getting-started/models for available models. Model names are specified directly in generation requests (e.g., POST https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation with "model": "qwen-plus"). The DashScope Python SDK (Generation.Models) provides programmatic model enumeration, but no REST endpoint for listing is documented in official sources.
Citations:
- 1: https://www.alibabacloud.com/help/en/model-studio/qwen-api-via-dashscope
- 2: https://www.alibabacloud.com/help/zh/doc-detail/3016809.html
- 3: https://help.aliyun.com/zh/model-studio/qwen-api-via-dashscope
- 4: https://www.aliyun.com
- 5: https://github.com/dashscope/dashscope-sdk-python
🏁 Script executed:
# Check the full context of the ListModels function
head -n 410 internal/entity/models/aliyun.go | tail -n 100Repository: infiniflow/ragflow
Length of output: 2690
🏁 Script executed:
# Find APIConfig struct definition and check if ApiKey is optional
rg "type APIConfig" -A 10 internal/entity/models/aliyun.goRepository: infiniflow/ragflow
Length of output: 44
🏁 Script executed:
# Search for all calls to ListModels to see how apiConfig is provided
rg "ListModels" --type goRepository: infiniflow/ragflow
Length of output: 2677
🏁 Script executed:
# Search for APIConfig struct definition across the codebase
rg "type APIConfig struct" -A 15 internal/entity/models/Repository: infiniflow/ragflow
Length of output: 377
🏁 Script executed:
# Check model_service.go to see how apiConfig is prepared before calling ListModels
rg "ListModels\(apiConfig\)" -B 20 internal/service/model_service.go | head -60Repository: infiniflow/ragflow
Length of output: 572
Address two issues in ListModels: remove empty body from GET request and add nil-guard for API key.
The code sends an empty JSON body with a GET request, which is semantically incorrect and can cause proxies/WAFs to reject the request. Additionally, *apiConfig.ApiKey is dereferenced without a nil check at line 378.
♻️ Proposed fix
url := fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.Models)
- // 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)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
- req.Header.Set("Content-Type", "application/json")
+ if apiConfig.ApiKey == nil {
+ return nil, fmt.Errorf("API key is required")
+ }
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey))🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/models/aliyun.go` around lines 365 - 378, In ListModels: stop
sending an empty JSON body with the GET by passing nil as the body to
http.NewRequest instead of bytes.NewBuffer(jsonData) and remove the json.Marshal
of an empty map; also add a nil-check for apiConfig.ApiKey before dereferencing
(guard *apiConfig.ApiKey or use a safe local variable) and only set the
Authorization header using that validated value (adjust the req.Header.Set calls
around req and apiConfig.ApiKey accordingly).
| // I need to get the model type, such as qwen3 is the prefix, the model type will be qwen. glm is the prefix, the model type will be glm. such as the model name: qwen3-0.6b, the model type will be qwen3 | ||
| // the model name is glm-4.7, the model type will be glm | ||
| modelType := strings.Split(*modelName, "-")[0] | ||
| if modelType == "qwen" || modelType == "glm" { | ||
| url = fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.AsyncChat) | ||
| } |
There was a problem hiding this comment.
Routing condition won't match qwen3 model names — likely bug.
For qwen3-0.6b, strings.Split(*modelName, "-")[0] returns "qwen3", not "qwen". The guard modelType == "qwen" || modelType == "glm" therefore never fires for qwen3 models, so they fall back to URLSuffix.Chat instead of URLSuffix.AsyncChat. The comment is also self-contradictory ("will be qwen" vs "will be qwen3").
🐛 Suggested fix
- // I need to get the model type, such as qwen3 is the prefix, the model type will be qwen. glm is the prefix, the model type will be glm. such as the model name: qwen3-0.6b, the model type will be qwen3
- // the model name is glm-4.7, the model type will be glm
- modelType := strings.Split(*modelName, "-")[0]
- if modelType == "qwen" || modelType == "glm" {
+ // Derive prefix-based model type, e.g. "qwen3-0.6b" -> "qwen3", "glm-4.7" -> "glm".
+ modelType := strings.Split(*modelName, "-")[0]
+ if strings.HasPrefix(modelType, "qwen") || modelType == "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 type, such as qwen3 is the prefix, the model type will be qwen. glm is the prefix, the model type will be glm. such as the model name: qwen3-0.6b, the model type will be qwen3 | |
| // the model name is glm-4.7, the model type will be glm | |
| modelType := strings.Split(*modelName, "-")[0] | |
| if modelType == "qwen" || modelType == "glm" { | |
| url = fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.AsyncChat) | |
| } | |
| // Derive prefix-based model type, e.g. "qwen3-0.6b" -> "qwen3", "glm-4.7" -> "glm". | |
| modelType := strings.Split(*modelName, "-")[0] | |
| if strings.HasPrefix(modelType, "qwen") || modelType == "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 72 - 77, The routing
condition misidentifies qwen3 models because modelType equals "qwen3" not
"qwen"; update the condition in siliconflow.go to use a prefix check (e.g.,
strings.HasPrefix(modelType, "qwen")) instead of strict equality so qwen3,
qwen2, etc. match, keep the glm equality as-is, and update the comment to
reflect that qwen* model types (like qwen3) should route to
z.URLSuffix.AsyncChat using z.BaseURL[region].
| } | ||
|
|
||
| thinking, answer := GetThinkingAndAnswer(chatModelConfig.ModelSeries, &content) | ||
| thinking, answer := GetThinkingAndAnswer(chatModelConfig.ModelType, &content) |
There was a problem hiding this comment.
Guard against nil chatModelConfig.ModelType.
GetThinkingAndAnswer dereferences *modelType unconditionally (see internal/entity/models/common.go). If chatModelConfig.ModelType is nil here (it's an optional *string), this path will panic. Either set a sensible fallback before calling, or fix the callee to nil-check.
🤖 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, The call to
GetThinkingAndAnswer(chatModelConfig.ModelType, &content) can panic when
chatModelConfig.ModelType is nil because GetThinkingAndAnswer dereferences the
pointer; before calling, ensure chatModelConfig.ModelType is non-nil by
providing a sensible default (e.g., set to a default model string) or perform a
nil-check and branch to a fallback path; alternatively update
GetThinkingAndAnswer to accept a nil *string and handle it safely (nil-check
inside GetThinkingAndAnswer). Reference symbols: adjust the caller in
siliconflow.go where GetThinkingAndAnswer(...) is invoked or modify
GetThinkingAndAnswer in internal/entity/models/common.go to guard against nil.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14379 +/- ##
=======================================
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:
|
What problem does this PR solve?
As title.
Type of change