Repository navigation
Go: add stream / think chat - #14242
Conversation
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
📝 WalkthroughWalkthroughLexer and parser add STREAM and SUPPORTED tokens and parsing; CLI distinguishes streaming vs non-stream chats and a new list_supported_models command; non-stream responses split into reasoning_content and answer; model driver APIs switch to structured APIConfig and ChatResponse; multiple model drivers and factory updated/added. Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant Parser
participant CLI as CLI(user_command)
participant Handler
participant Service
participant Model
User->>Parser: "STREAM CHAT ..." or "CHAT ..." input
Parser->>Parser: tokenize (STREAM/CHAT/THINK/SUPPORTED) and build Command{thinking?, stream?, provider?, instance?}
Parser-->>CLI: parsed Command
alt stream = true
CLI->>Handler: HTTP request (stream=true, thinking?)
Handler->>Service: ChatToModel(..., apiConfig, ChatConfig{Thinking, stream:true})
Service->>Model: ChatStreamlyWithSender(..., apiConfig, ChatConfig)
Model-->>Service: SSE chunks
Service-->>Handler: proxied SSE events
Handler->>CLI: incremental output (reasoning then answer)
CLI-->>User: streamed output
else stream = false
CLI->>Handler: HTTP request (stream=false, thinking?)
Handler->>Service: ChatToModel(..., apiConfig, ChatConfig{Thinking, stream:false})
Service->>Model: Chat(..., apiConfig, ChatConfig)
Model-->>Service: ChatResponse{Answer, ReasonContent}
Service-->>Handler: ChatResponse
Handler->>CLI: NonStreamResponse{reasoning_content, answer}
CLI-->>User: full response
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 6
🧹 Nitpick comments (2)
internal/entity/models/types.go (1)
13-16: JSON tag inconsistency with other response structures.The JSON tag
reason_contentdiffers fromreasoning_contentused ininternal/cli/response.go(NonStreamResponse.ReasoningContent) and the handler's manual JSON response. While the handler constructs JSON manually (so this tag isn't used there), maintaining consistency across the codebase would improve maintainability.♻️ Suggested fix for consistency
type ChatResponse struct { Answer *string `json:"answer"` - ReasonContent *string `json:"reason_content"` + ReasonContent *string `json:"reasoning_content"` }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/entity/models/types.go` around lines 13 - 16, The ChatResponse struct's JSON tag is inconsistent: update the ReasonContent field in ChatResponse (in types.go) to use `json:"reasoning_content"` (matching NonStreamResponse.ReasoningContent in internal/cli/response.go and the handler's manual JSON) so tags are consistent across the codebase; keep the field name ReasonContent but change only its JSON tag and run any related serialization consumers to verify compatibility.internal/entity/models/zhipu-ai.go (1)
148-165: Consider returningnilforReasonContentwhen thinking is disabled.When
Thinkingisfalseornil,ReasonContentis set to a pointer to an empty string rather thannil. Consumers (like the CLI atresponse.go:139) check for empty string, but semanticallynilbetter represents "not present" versus "present but empty".Additionally, the error message at line 152 says "invalid content format" but should specify "reasoning_content" for clarity.
♻️ Proposed improvement
var reasonContent string if chatModelConfig.Thinking != nil && *chatModelConfig.Thinking { reasonContent, ok = messageMap["reasoning_content"].(string) if !ok { - return nil, fmt.Errorf("invalid content format") + return nil, fmt.Errorf("invalid reasoning_content format") } // if first char of reasonContent is \n remove the '\n' if reasonContent != "" && reasonContent[0] == '\n' { reasonContent = reasonContent[1:] } } chatResponse := &ChatResponse{ Answer: &content, - ReasonContent: &reasonContent, + ReasonContent: nil, + } + if reasonContent != "" { + chatResponse.ReasonContent = &reasonContent } return chatResponse, nil🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/entity/models/zhipu-ai.go` around lines 148 - 165, The code sets ReasonContent to a pointer to an empty string even when thinking is disabled and uses a generic error message; update the logic around chatModelConfig.Thinking and reasonContent so that when Thinking is nil/false you leave ChatResponse.ReasonContent as nil (not a pointer to ""), and when extracting reasoning_content from messageMap return a clearer error like "invalid reasoning_content format" if the type assertion fails; adjust the construction of the ChatResponse (and any variable initialization of reasonContent) so ReasonContent is only assigned a non-nil pointer when thinking is enabled and a valid string was parsed.
🤖 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/cli/user_command.go`:
- Around line 1520-1531: The error messages inside the ChatToModel function are
incorrect copy-paste references to "list instance models"; update all fmt.Errorf
messages in ChatToModel (the error handling after c.HTTPClient.Request, the
non-200 status branch, and the json.Unmarshal failure) to use a correct,
consistent description like "chat to model" or "ChatToModel" and include the
same wrapped error/details (e.g., HTTP status and body, or wrapped JSON
unmarshal error) while keeping the existing variables resp, err, and result
unchanged.
- Around line 1438-1440: The code performs unchecked type assertions on
cmd.Params for "message", "thinking", and "stream" which can panic if keys are
missing or have unexpected types; update the assignment to use the comma-ok
idiom (e.g., v, ok := cmd.Params["message"].(string)) and handle missing/invalid
cases by providing a sensible default or returning an error; do the same for
"thinking" and "stream" using bool assertions and ensure any subsequent use of
message, thinking, or stream checks the validated values before proceeding
(reference cmd.Params, and the local variables message, thinking, stream).
- Around line 1470-1493: The stream-handling branch drops the very first chunk
because when reasoningPrint or messagePrint is true the code prints the header
("Thinking: " / "Answer: ") but does not print the stripped data for that same
iteration; update the logic in the blocks that check reasoningPrint and
messagePrint (working with variables data, reasoningPrint, messagePrint,
thinking, and fullMessage) so after emitting the header you also print the
current data (and call os.Stdout.Sync) and, for the message branch, append that
data to fullMessage; keep the existing behavior that only the header is printed
once by toggling the flags to false.
In `@internal/cli/user_parser.go`:
- Around line 2218-2239: In Parser.parseStreamCommand, avoid the nil deref when
the token after STREAM isn't TokenChat or TokenThink by validating p.curToken
and returning a syntax error instead of proceeding with a nil command: after
calling p.nextToken(), check if p.curToken.Type is TokenChat or TokenThink and
only call parseChatCommand()/parseThinkCommand() accordingly; if it is neither,
return an error (e.g., fmt.Errorf("unexpected token after STREAM: %v",
p.curToken.Type)) so you never reach command.Params when command is nil;
alternatively, guard before setting command.Params by checking command != nil
and returning an explicit syntax error.
In `@internal/entity/models/zhipu-ai.go`:
- Around line 61-66: The code builds url using region (from
chatModelConfig.Region) and directly indexing z.BaseURL[region]; add a presence
check on the z.BaseURL map before formatting the URL: verify that z.BaseURL
contains the chosen region key (or fall back to a safe default base URL or
return an error) before calling fmt.Sprintf with z.URLSuffix.Chat, and if the
key is missing log/return a clear error or set region to a known valid
key—update the logic around the region variable and the url construction (the
block that sets region, checks chatModelConfig.Region, and the fmt.Sprintf line)
to perform this validation.
- Around line 78-92: The non-stream Chat request is missing the "thinking"
parameter so when chatModelConfig.Thinking is true the API won't return
reasoning_content; update the Chat request body construction where reqBody is
built (in internal/entity/models/zhipu-ai.go) to include reqBody["thinking"] =
*chatModelConfig.Thinking (guarded by a nil check like the other fields) the
same way ChatStreamlyWithSender sends it, ensuring the Chat method and any logic
that expects reasoning_content (e.g., handling at line 152) receives the
parameter.
---
Nitpick comments:
In `@internal/entity/models/types.go`:
- Around line 13-16: The ChatResponse struct's JSON tag is inconsistent: update
the ReasonContent field in ChatResponse (in types.go) to use
`json:"reasoning_content"` (matching NonStreamResponse.ReasoningContent in
internal/cli/response.go and the handler's manual JSON) so tags are consistent
across the codebase; keep the field name ReasonContent but change only its JSON
tag and run any related serialization consumers to verify compatibility.
In `@internal/entity/models/zhipu-ai.go`:
- Around line 148-165: The code sets ReasonContent to a pointer to an empty
string even when thinking is disabled and uses a generic error message; update
the logic around chatModelConfig.Thinking and reasonContent so that when
Thinking is nil/false you leave ChatResponse.ReasonContent as nil (not a pointer
to ""), and when extracting reasoning_content from messageMap return a clearer
error like "invalid reasoning_content format" if the type assertion fails;
adjust the construction of the ChatResponse (and any variable initialization of
reasonContent) so ReasonContent is only assigned a non-nil pointer when thinking
is enabled and a valid string was parsed.
🪄 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: 19515ad7-eb47-4e83-ae2d-e5cb40e39838
📒 Files selected for processing (11)
internal/cli/lexer.gointernal/cli/parser.gointernal/cli/response.gointernal/cli/types.gointernal/cli/user_command.gointernal/cli/user_parser.gointernal/entity/models/dummy.gointernal/entity/models/types.gointernal/entity/models/zhipu-ai.gointernal/handler/providers.gointernal/service/model_service.go
| message := cmd.Params["message"].(string) | ||
| reasoning := cmd.Params["reasoning"].(bool) | ||
| thinking := cmd.Params["thinking"].(bool) | ||
| stream := cmd.Params["stream"].(bool) |
There was a problem hiding this comment.
Type assertions without checking could cause panics.
If these parameters are missing from cmd.Params, the type assertions will panic. Consider adding defensive checks or using the comma-ok idiom.
🛡️ Proposed defensive fix
- message := cmd.Params["message"].(string)
- thinking := cmd.Params["thinking"].(bool)
- stream := cmd.Params["stream"].(bool)
+ message, ok := cmd.Params["message"].(string)
+ if !ok {
+ return nil, fmt.Errorf("message parameter is required")
+ }
+ thinking, _ := cmd.Params["thinking"].(bool)
+ stream, _ := cmd.Params["stream"].(bool)📝 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.
| message := cmd.Params["message"].(string) | |
| reasoning := cmd.Params["reasoning"].(bool) | |
| thinking := cmd.Params["thinking"].(bool) | |
| stream := cmd.Params["stream"].(bool) | |
| message, ok := cmd.Params["message"].(string) | |
| if !ok { | |
| return nil, fmt.Errorf("message parameter is required") | |
| } | |
| thinking, _ := cmd.Params["thinking"].(bool) | |
| stream, _ := cmd.Params["stream"].(bool) |
🤖 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 1438 - 1440, The code performs
unchecked type assertions on cmd.Params for "message", "thinking", and "stream"
which can panic if keys are missing or have unexpected types; update the
assignment to use the comma-ok idiom (e.g., v, ok :=
cmd.Params["message"].(string)) and handle missing/invalid cases by providing a
sensible default or returning an error; do the same for "thinking" and "stream"
using bool assertions and ensure any subsequent use of message, thinking, or
stream checks the validated values before proceeding (reference cmd.Params, and
the local variables message, thinking, stream).
| if strings.HasPrefix(data, "[REASONING]") { | ||
| data = strings.TrimPrefix(data, "[REASONING]") | ||
| if reasoningPrint { | ||
| fmt.Print("Thinking: ") | ||
| reasoningPrint = false | ||
| } else { | ||
| fmt.Print(data) | ||
| } | ||
| fmt.Print("Answer: ") | ||
| messagePrint = false | ||
| } else { | ||
| fmt.Print(data) | ||
| os.Stdout.Sync() | ||
| fullMessage.WriteString(data) | ||
| } | ||
| if strings.HasPrefix(data, "[MESSAGE]") { | ||
| data = strings.TrimPrefix(data, "[MESSAGE]") | ||
| if messagePrint { | ||
| if thinking { | ||
| fmt.Println() | ||
| } | ||
| fmt.Print("Answer: ") | ||
| messagePrint = false | ||
| } else { | ||
| fmt.Print(data) | ||
| os.Stdout.Sync() | ||
| fullMessage.WriteString(data) | ||
| } | ||
| } |
There was a problem hiding this comment.
Stream output logic discards first chunk content.
When reasoningPrint is true (first reasoning chunk), the code prints "Thinking: " but then doesn't output data for that iteration. Similarly for message output - the first chunk's content after stripping the prefix is discarded.
🐛 Proposed fix to print first chunk content
if strings.HasPrefix(data, "[REASONING]") {
data = strings.TrimPrefix(data, "[REASONING]")
if reasoningPrint {
fmt.Print("Thinking: ")
reasoningPrint = false
- } else {
- fmt.Print(data)
}
+ fmt.Print(data)
os.Stdout.Sync()
}
if strings.HasPrefix(data, "[MESSAGE]") {
data = strings.TrimPrefix(data, "[MESSAGE]")
if messagePrint {
if thinking {
fmt.Println()
}
fmt.Print("Answer: ")
messagePrint = false
- } else {
- fmt.Print(data)
- os.Stdout.Sync()
- fullMessage.WriteString(data)
}
+ fmt.Print(data)
+ os.Stdout.Sync()
+ fullMessage.WriteString(data)
}📝 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 strings.HasPrefix(data, "[REASONING]") { | |
| data = strings.TrimPrefix(data, "[REASONING]") | |
| if reasoningPrint { | |
| fmt.Print("Thinking: ") | |
| reasoningPrint = false | |
| } else { | |
| fmt.Print(data) | |
| } | |
| fmt.Print("Answer: ") | |
| messagePrint = false | |
| } else { | |
| fmt.Print(data) | |
| os.Stdout.Sync() | |
| fullMessage.WriteString(data) | |
| } | |
| if strings.HasPrefix(data, "[MESSAGE]") { | |
| data = strings.TrimPrefix(data, "[MESSAGE]") | |
| if messagePrint { | |
| if thinking { | |
| fmt.Println() | |
| } | |
| fmt.Print("Answer: ") | |
| messagePrint = false | |
| } else { | |
| fmt.Print(data) | |
| os.Stdout.Sync() | |
| fullMessage.WriteString(data) | |
| } | |
| } | |
| if strings.HasPrefix(data, "[REASONING]") { | |
| data = strings.TrimPrefix(data, "[REASONING]") | |
| if reasoningPrint { | |
| fmt.Print("Thinking: ") | |
| reasoningPrint = false | |
| } | |
| fmt.Print(data) | |
| os.Stdout.Sync() | |
| } | |
| if strings.HasPrefix(data, "[MESSAGE]") { | |
| data = strings.TrimPrefix(data, "[MESSAGE]") | |
| if messagePrint { | |
| if thinking { | |
| fmt.Println() | |
| } | |
| fmt.Print("Answer: ") | |
| messagePrint = false | |
| } | |
| fmt.Print(data) | |
| os.Stdout.Sync() | |
| fullMessage.WriteString(data) | |
| } |
🤖 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 1470 - 1493, The stream-handling
branch drops the very first chunk because when reasoningPrint or messagePrint is
true the code prints the header ("Thinking: " / "Answer: ") but does not print
the stripped data for that same iteration; update the logic in the blocks that
check reasoningPrint and messagePrint (working with variables data,
reasoningPrint, messagePrint, thinking, and fullMessage) so after emitting the
header you also print the current data (and call os.Stdout.Sync) and, for the
message branch, append that data to fullMessage; keep the existing behavior that
only the header is printed once by toggling the flags to false.
| resp, err := c.HTTPClient.Request("POST", url, true, "web", nil, payload) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to list instance models: %w", err) | ||
| } | ||
|
|
||
| fmt.Println() | ||
| if resp.StatusCode != 200 { | ||
| return nil, fmt.Errorf("failed to list instance models: HTTP %d, body: %s", resp.StatusCode, string(resp.Body)) | ||
| } | ||
|
|
||
| var result NonStreamResponse | ||
| if err = json.Unmarshal(resp.Body, &result); err != nil { | ||
| return nil, fmt.Errorf("failed to list instance models: invalid JSON (%w)", err) |
There was a problem hiding this comment.
Copy-paste error: misleading error messages.
The error messages reference "list instance models" but this is the ChatToModel function. These appear to be leftover from copy-pasting.
✏️ Proposed fix for error messages
resp, err := c.HTTPClient.Request("POST", url, true, "web", nil, payload)
if err != nil {
- return nil, fmt.Errorf("failed to list instance models: %w", err)
+ return nil, fmt.Errorf("failed to chat to model: %w", err)
}
if resp.StatusCode != 200 {
- return nil, fmt.Errorf("failed to list instance models: HTTP %d, body: %s", resp.StatusCode, string(resp.Body))
+ return nil, fmt.Errorf("failed to chat to model: HTTP %d, body: %s", resp.StatusCode, string(resp.Body))
}
var result NonStreamResponse
if err = json.Unmarshal(resp.Body, &result); err != nil {
- return nil, fmt.Errorf("failed to list instance models: invalid JSON (%w)", err)
+ return nil, fmt.Errorf("failed to chat to model: invalid JSON (%w)", err)
}📝 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.
| resp, err := c.HTTPClient.Request("POST", url, true, "web", nil, payload) | |
| if err != nil { | |
| return nil, fmt.Errorf("failed to list instance models: %w", err) | |
| } | |
| fmt.Println() | |
| if resp.StatusCode != 200 { | |
| return nil, fmt.Errorf("failed to list instance models: HTTP %d, body: %s", resp.StatusCode, string(resp.Body)) | |
| } | |
| var result NonStreamResponse | |
| if err = json.Unmarshal(resp.Body, &result); err != nil { | |
| return nil, fmt.Errorf("failed to list instance models: invalid JSON (%w)", err) | |
| resp, err := c.HTTPClient.Request("POST", url, true, "web", nil, payload) | |
| if err != nil { | |
| return nil, fmt.Errorf("failed to chat to model: %w", err) | |
| } | |
| if resp.StatusCode != 200 { | |
| return nil, fmt.Errorf("failed to chat to model: HTTP %d, body: %s", resp.StatusCode, string(resp.Body)) | |
| } | |
| var result NonStreamResponse | |
| if err = json.Unmarshal(resp.Body, &result); err != nil { | |
| return nil, fmt.Errorf("failed to chat to model: invalid JSON (%w)", err) | |
| } |
🤖 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 1520 - 1531, The error messages
inside the ChatToModel function are incorrect copy-paste references to "list
instance models"; update all fmt.Errorf messages in ChatToModel (the error
handling after c.HTTPClient.Request, the non-200 status branch, and the
json.Unmarshal failure) to use a correct, consistent description like "chat to
model" or "ChatToModel" and include the same wrapped error/details (e.g., HTTP
status and body, or wrapped JSON unmarshal error) while keeping the existing
variables resp, err, and result unchanged.
| func (p *Parser) parseStreamCommand() (*Command, error) { | ||
|
|
||
| p.nextToken() // consume STREAM | ||
|
|
||
| var command *Command | ||
| var err error | ||
|
|
||
| if p.curToken.Type == TokenChat { | ||
| command, err = p.parseChatCommand() | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| } else if p.curToken.Type == TokenThink { | ||
| command, err = p.parseThinkCommand() | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| } | ||
|
|
||
| command.Params["stream"] = true | ||
| return command, nil | ||
| } |
There was a problem hiding this comment.
Nil pointer dereference if token after STREAM is neither CHAT nor THINK.
If the token following STREAM is not TokenChat or TokenThink, command remains nil and line 2237 will panic when accessing command.Params["stream"].
🐛 Proposed fix to handle invalid syntax
func (p *Parser) parseStreamCommand() (*Command, error) {
p.nextToken() // consume STREAM
var command *Command
var err error
if p.curToken.Type == TokenChat {
command, err = p.parseChatCommand()
if err != nil {
return nil, err
}
} else if p.curToken.Type == TokenThink {
command, err = p.parseThinkCommand()
if err != nil {
return nil, err
}
+ } else {
+ return nil, fmt.Errorf("expected CHAT or THINK after STREAM")
}
command.Params["stream"] = true
return command, 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.
| func (p *Parser) parseStreamCommand() (*Command, error) { | |
| p.nextToken() // consume STREAM | |
| var command *Command | |
| var err error | |
| if p.curToken.Type == TokenChat { | |
| command, err = p.parseChatCommand() | |
| if err != nil { | |
| return nil, err | |
| } | |
| } else if p.curToken.Type == TokenThink { | |
| command, err = p.parseThinkCommand() | |
| if err != nil { | |
| return nil, err | |
| } | |
| } | |
| command.Params["stream"] = true | |
| return command, nil | |
| } | |
| func (p *Parser) parseStreamCommand() (*Command, error) { | |
| p.nextToken() // consume STREAM | |
| var command *Command | |
| var err error | |
| if p.curToken.Type == TokenChat { | |
| command, err = p.parseChatCommand() | |
| if err != nil { | |
| return nil, err | |
| } | |
| } else if p.curToken.Type == TokenThink { | |
| command, err = p.parseThinkCommand() | |
| if err != nil { | |
| return nil, err | |
| } | |
| } else { | |
| return nil, fmt.Errorf("expected CHAT or THINK after STREAM") | |
| } | |
| command.Params["stream"] = true | |
| return command, nil | |
| } |
🤖 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 2218 - 2239, In
Parser.parseStreamCommand, avoid the nil deref when the token after STREAM isn't
TokenChat or TokenThink by validating p.curToken and returning a syntax error
instead of proceeding with a nil command: after calling p.nextToken(), check if
p.curToken.Type is TokenChat or TokenThink and only call
parseChatCommand()/parseThinkCommand() accordingly; if it is neither, return an
error (e.g., fmt.Errorf("unexpected token after STREAM: %v", p.curToken.Type))
so you never reach command.Params when command is nil; alternatively, guard
before setting command.Params by checking command != nil and returning an
explicit syntax error.
| var region = "default" | ||
| if chatModelConfig.Region != nil { | ||
| region = *chatModelConfig.Region | ||
| } | ||
|
|
||
| url := fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.Chat) |
There was a problem hiding this comment.
Add validation for region key existence in BaseURL map.
If region key doesn't exist in z.BaseURL, the map access returns an empty string, resulting in a malformed URL (e.g., "/chat/completions" instead of "https://api.example.com/chat/completions"). This will cause confusing HTTP errors.
🛡️ Proposed fix to validate region key
var region = "default"
if chatModelConfig.Region != nil {
region = *chatModelConfig.Region
}
+ baseURL, ok := z.BaseURL[region]
+ if !ok {
+ return nil, fmt.Errorf("region %q not found in BaseURL configuration", region)
+ }
+
- url := fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.Chat)
+ url := fmt.Sprintf("%s/%s", baseURL, z.URLSuffix.Chat)📝 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 region = "default" | |
| if chatModelConfig.Region != nil { | |
| region = *chatModelConfig.Region | |
| } | |
| url := fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.Chat) | |
| var region = "default" | |
| if chatModelConfig.Region != nil { | |
| region = *chatModelConfig.Region | |
| } | |
| baseURL, ok := z.BaseURL[region] | |
| if !ok { | |
| return nil, fmt.Errorf("region %q not found in BaseURL configuration", region) | |
| } | |
| url := fmt.Sprintf("%s/%s", baseURL, z.URLSuffix.Chat) |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/models/zhipu-ai.go` around lines 61 - 66, The code builds url
using region (from chatModelConfig.Region) and directly indexing
z.BaseURL[region]; add a presence check on the z.BaseURL map before formatting
the URL: verify that z.BaseURL contains the chosen region key (or fall back to a
safe default base URL or return an error) before calling fmt.Sprintf with
z.URLSuffix.Chat, and if the key is missing log/return a clear error or set
region to a known valid key—update the logic around the region variable and the
url construction (the block that sets region, checks chatModelConfig.Region, and
the fmt.Sprintf line) to perform this validation.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14242 +/- ##
=======================================
Coverage 96.66% 96.66%
=======================================
Files 10 10
Lines 690 690
Branches 108 108
=======================================
Hits 667 667
Misses 8 8
Partials 15 15 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
Signed-off-by: Jin Hai <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (1)
internal/entity/models/zhipu-ai.go (1)
61-66:⚠️ Potential issue | 🟡 MinorValidate the region before indexing
z.BaseURL.This still does a direct
z.BaseURL[region]lookup. An unsupported region falls through to"", so the request is built with a malformed URL instead of failing with a clear configuration error.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/entity/models/zhipu-ai.go` around lines 61 - 66, The code currently defaults region to "default" and then directly indexes z.BaseURL[region] when building url, which can yield an empty string for unsupported regions; update the logic (around the region variable, chatModelConfig.Region usage, and the url construction that uses z.BaseURL and z.URLSuffix.Chat) to validate that the chosen region key exists in z.BaseURL before formatting the URL, and if it does not exist return or surface a clear configuration error (e.g., return an error or panic) instead of constructing a malformed URL.
🤖 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/zhipu-ai.go`:
- Around line 78-80: The Chat() handler currently copies chatModelConfig.Stream
into the request body (reqBody["stream"] = *chatModelConfig.Stream) which allows
streaming=true to be sent but Chat() expects a single JSON response; update
Chat() to disallow streaming by checking chatModelConfig.Stream and if non-nil
and true return an error (or override it to false before adding to reqBody) so
that streaming responses (handled correctly by ChatStreamlyWithSender()) are
never requested by Chat(); reference the Chat() function and the
chatModelConfig.Stream usage to locate the change.
- Around line 203-205: The ChatStreamlyWithSender() implementation parses SSE
events but builds requests that may have stream=false; ensure the request always
requests SSE: in ChatStreamlyWithSender() update the logic around
reqBody["stream"] (currently reading chatModelConfig.Stream) to either
unconditionally set reqBody["stream"] = true or validate chatModelConfig.Stream
and return an error if it's false/nil, so the scanner loop that reads
SSE-formatted events (the SSE parsing starting around the current lines ~264)
always receives streaming responses.
---
Duplicate comments:
In `@internal/entity/models/zhipu-ai.go`:
- Around line 61-66: The code currently defaults region to "default" and then
directly indexes z.BaseURL[region] when building url, which can yield an empty
string for unsupported regions; update the logic (around the region variable,
chatModelConfig.Region usage, and the url construction that uses z.BaseURL and
z.URLSuffix.Chat) to validate that the chosen region key exists in z.BaseURL
before formatting the URL, and if it does not exist return or surface a clear
configuration error (e.g., return an error or panic) instead of constructing a
malformed URL.
🪄 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: 006e5e08-ca12-46ed-8c51-3bd2a81d4c77
📒 Files selected for processing (1)
internal/entity/models/zhipu-ai.go
| if chatModelConfig.Stream != nil { | ||
| reqBody["stream"] = *chatModelConfig.Stream | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
cd internal/entity/models && wc -l zhipu-ai.goRepository: infiniflow/ragflow
Length of output: 77
🏁 Script executed:
cat -n internal/entity/models/zhipu-ai.go | head -150Repository: infiniflow/ragflow
Length of output: 5008
🏁 Script executed:
cat -n internal/entity/models/zhipu-ai.go | sed -n '140,300p'Repository: infiniflow/ragflow
Length of output: 5249
Prevent Chat() from accepting streaming configuration.
Chat() reads the full response body and unmarshals it as a single JSON document (line 140). When stream=true is sent, the Zhipu AI API returns Server-Sent Events format (newline-delimited JSON with "data:" prefix), which json.Unmarshal() cannot parse as a single document. The parser expects the choices[0].message.content structure from a non-streaming response, causing the unmarshal to fail.
The ChatStreamlyWithSender() method (lines 184+) properly handles streaming responses using bufio.NewScanner (line 264) and line-by-line parsing with SSE format handling.
Either reject stream=true in Chat() with an error, or ensure stream is always false:
Suggested fix
- if chatModelConfig.Stream != nil {
- reqBody["stream"] = *chatModelConfig.Stream
- }
+ if chatModelConfig.Stream != nil && *chatModelConfig.Stream {
+ return nil, fmt.Errorf("Chat does not support stream=true; use ChatStreamlyWithSender")
+ }
+ reqBody["stream"] = false🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/models/zhipu-ai.go` around lines 78 - 80, The Chat() handler
currently copies chatModelConfig.Stream into the request body (reqBody["stream"]
= *chatModelConfig.Stream) which allows streaming=true to be sent but Chat()
expects a single JSON response; update Chat() to disallow streaming by checking
chatModelConfig.Stream and if non-nil and true return an error (or override it
to false before adding to reqBody) so that streaming responses (handled
correctly by ChatStreamlyWithSender()) are never requested by Chat(); reference
the Chat() function and the chatModelConfig.Stream usage to locate the change.
| if chatModelConfig.Stream != nil { | ||
| reqBody["stream"] = *chatModelConfig.Stream | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
find . -name "zhipu-ai.go" -type fRepository: infiniflow/ragflow
Length of output: 98
🏁 Script executed:
cat -n internal/entity/models/zhipu-ai.go | sed -n '190,220p'Repository: infiniflow/ragflow
Length of output: 1029
🏁 Script executed:
rg "ChatStreamlyWithSender" internal/entity/models/zhipu-ai.go -A 30 -B 5Repository: infiniflow/ragflow
Length of output: 1081
🏁 Script executed:
cat -n internal/entity/models/zhipu-ai.go | sed -n '175,280p'Repository: infiniflow/ragflow
Length of output: 3454
🏁 Script executed:
rg "ChatStreamlyWithSender" internal/entity/models/zhipu-ai.go -A 100 | head -120Repository: infiniflow/ragflow
Length of output: 2723
🏁 Script executed:
cat -n internal/entity/models/zhipu-ai.go | sed -n '280,310p'Repository: infiniflow/ragflow
Length of output: 903
🏁 Script executed:
rg "ChatStreamlyWithSender" --include="*.go" -B 3 -A 3Repository: infiniflow/ragflow
Length of output: 503
🏁 Script executed:
rg "ChatStreamlyWithSender" -g "*.go" -B 3 -A 3Repository: infiniflow/ragflow
Length of output: 2666
🏁 Script executed:
rg "ChatConfig" internal/entity/models/ -g "*.go" -B 2 -A 10 | head -80Repository: infiniflow/ragflow
Length of output: 5005
Force stream=true in ChatStreamlyWithSender().
The method always parses SSE format (lines 264+), extracting data from SSE-formatted events and waiting for the [DONE] sentinel. However, the request defaults to stream=false (line 199), and if chatModelConfig.Stream is nil or false, the API returns a normal JSON response instead of SSE. The scanner loop cannot parse this format and will fail or produce incorrect results. The method should either always enforce stream=true or reject stream=false with an error.
Suggested fix
- if chatModelConfig.Stream != nil {
- reqBody["stream"] = *chatModelConfig.Stream
- }
+ if chatModelConfig.Stream != nil && !*chatModelConfig.Stream {
+ return fmt.Errorf("ChatStreamlyWithSender requires stream=true")
+ }
+ reqBody["stream"] = true📝 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 chatModelConfig.Stream != nil { | |
| reqBody["stream"] = *chatModelConfig.Stream | |
| } | |
| if chatModelConfig.Stream != nil && !*chatModelConfig.Stream { | |
| return fmt.Errorf("ChatStreamlyWithSender requires stream=true") | |
| } | |
| reqBody["stream"] = true |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/models/zhipu-ai.go` around lines 203 - 205, The
ChatStreamlyWithSender() implementation parses SSE events but builds requests
that may have stream=false; ensure the request always requests SSE: in
ChatStreamlyWithSender() update the logic around reqBody["stream"] (currently
reading chatModelConfig.Stream) to either unconditionally set reqBody["stream"]
= true or validate chatModelConfig.Stream and return an error if it's false/nil,
so the scanner loop that reads SSE-formatted events (the SSE parsing starting
around the current lines ~264) always receives streaming responses.
Signed-off-by: Jin Hai <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 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 252-255: The loop over modelClearThinking can nil-deref
model.Thinking when a model.Name matches; before setting
model.Thinking.ClearContent in that block ensure model.Thinking is initialized
(e.g., if model.Thinking == nil then assign a new Thinking struct) so you never
set a field on a nil pointer; update the code inside the for loop that checks
strings.HasPrefix(model.Name, modelPrefix) to allocate model.Thinking when
needed before assigning ClearContent.
- Line 168: The code is passing provider.URL (a map[string]string) directly into
fmt.Sprintf which prints the map rather than a base URL; update each fmt.Sprintf
call that currently uses provider.URL to instead use the concrete string
provider.URL["default"] (or providerURL := provider.URL["default"]) and pass
that into fmt.Sprintf, and add a nil/missing-key guard (e.g., check provider.URL
!= nil and the "default" key exists, with a sensible fallback or error) so URL
construction produces a proper string.
🪄 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: 34ceb9df-2378-430c-aa9e-ddf82d55c68d
📒 Files selected for processing (2)
conf/models/zhipu-ai.jsoninternal/entity/model.go
| Features Features `json:"features"` | ||
| ModelDriver models.ModelDriver | ||
| Name string `json:"name"` | ||
| URL map[string]string `json:"url"` |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Verify Provider.URL type and URL formatting call sites.
ast-grep --pattern $'type Provider struct { $$$ URL map[string]string $$$ }'
rg -n -C2 --type go 'fmt\.Sprintf\("%s%s",\s*provider\.URL,\s*provider\.URLSuffix\.[A-Za-z]+\)'Repository: infiniflow/ragflow
Length of output: 1143
🏁 Script executed:
cat -n internal/entity/model.go | sed -n '160,180p'Repository: infiniflow/ragflow
Length of output: 898
🏁 Script executed:
cat -n internal/entity/model.go | sed -n '380,410p'Repository: infiniflow/ragflow
Length of output: 1536
🏁 Script executed:
# Check Provider struct definition thoroughly
rg -A 50 -B 5 "^type Provider struct" internal/entity/model.goRepository: infiniflow/ragflow
Length of output: 1797
🏁 Script executed:
# Check how Provider.URL map is initialized or populated
rg -n "\.URL\s*=" internal/entity/model.go | head -20Repository: infiniflow/ragflow
Length of output: 44
🏁 Script executed:
# Find provider JSON configuration files
fd -e json "provider" -o "config"Repository: infiniflow/ragflow
Length of output: 193
🏁 Script executed:
# Look for example JSON or test files with Provider data
rg -l "\"url\"" --type json | head -5Repository: infiniflow/ragflow
Length of output: 178
🏁 Script executed:
# Search for any comments or documentation about URL map keys
rg -B3 -A3 "URL.*map\[string\]string" internal/entity/model.goRepository: infiniflow/ragflow
Length of output: 374
🏁 Script executed:
# Check if there's any place where specific URL keys are referenced
rg "\.URL\[" internal/Repository: infiniflow/ragflow
Length of output: 44
🏁 Script executed:
cat conf/models/openai.json | head -50Repository: infiniflow/ragflow
Length of output: 930
🏁 Script executed:
cat conf/models/xai.json | head -50Repository: infiniflow/ragflow
Length of output: 941
🏁 Script executed:
# Check if URL is a single string or map in actual config
rg -A 5 '"url"' conf/models/openai.jsonRepository: infiniflow/ragflow
Length of output: 174
URL construction is using a map where a string is required.
provider.URL is a map[string]string (as confirmed in JSON configs with structure "url": { "default": "https://..." }), but Lines 387, 390, 391, 394, and 397 pass it directly to %s in fmt.Sprintf. This produces malformed output like map[default:https://...] instead of a valid URL. Extract the concrete base URL value using provider.URL["default"].
💡 Proposed fix
func (pm *ProviderManager) GetModelUrl(providerName, modelName, modelType string) (*string, *string, error) {
provider := pm.FindProvider(providerName)
if provider == nil {
return nil, nil, fmt.Errorf("provider '%s' not found", providerName)
}
+ baseURL, ok := provider.URL["default"]
+ if !ok || baseURL == "" {
+ return nil, nil, fmt.Errorf("provider '%s' default base URL not configured", providerName)
+ }
model := pm.findModel(provider, modelName)
if model == nil {
return nil, nil, fmt.Errorf("model '%s' not found", modelName)
}
if !model.ModelTypeMap[modelType] {
return nil, nil, fmt.Errorf("model '%s' does not support model type '%s'", modelName, modelType)
}
switch modelType {
case "chat":
- url := fmt.Sprintf("%s%s", provider.URL, provider.URLSuffix.Chat)
+ url := fmt.Sprintf("%s%s", baseURL, provider.URLSuffix.Chat)
return &url, nil, nil
case "async_chat":
- chatUrl := fmt.Sprintf("%s%s", provider.URL, provider.URLSuffix.AsyncChat)
- resultUrl := fmt.Sprintf("%s%s", provider.URL, provider.URLSuffix.AsyncResult)
+ chatUrl := fmt.Sprintf("%s%s", baseURL, provider.URLSuffix.AsyncChat)
+ resultUrl := fmt.Sprintf("%s%s", baseURL, provider.URLSuffix.AsyncResult)
return &chatUrl, &resultUrl, nil
case "embedding":
- url := fmt.Sprintf("%s%s", provider.URL, provider.URLSuffix.Embedding)
+ url := fmt.Sprintf("%s%s", baseURL, provider.URLSuffix.Embedding)
return &url, nil, nil
case "rerank":
- url := fmt.Sprintf("%s%s", provider.URL, provider.URLSuffix.Rerank)
+ url := fmt.Sprintf("%s%s", baseURL, provider.URLSuffix.Rerank)
return &url, nil, nil
default:
return nil, nil, fmt.Errorf("model '%s' does not support model type '%s'", modelName, modelType)
}
}🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/model.go` at line 168, The code is passing provider.URL (a
map[string]string) directly into fmt.Sprintf which prints the map rather than a
base URL; update each fmt.Sprintf call that currently uses provider.URL to
instead use the concrete string provider.URL["default"] (or providerURL :=
provider.URL["default"]) and pass that into fmt.Sprintf, and add a
nil/missing-key guard (e.g., check provider.URL != nil and the "default" key
exists, with a sensible fallback or error) so URL construction produces a proper
string.
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 7
♻️ Duplicate comments (2)
internal/entity/models/zhipu-ai.go (2)
203-205:⚠️ Potential issue | 🟠 MajorForce streaming mode for
ChatStreamlyWithSender.This method only parses SSE, but the request can still be sent with
stream=falseor default to false. That makes the scanner parse a normal JSON response as SSE. This was already flagged previously and still applies.Suggested fix
- if chatModelConfig.Stream != nil { - reqBody["stream"] = *chatModelConfig.Stream - } + if chatModelConfig.Stream != nil && !*chatModelConfig.Stream { + return fmt.Errorf("ChatStreamlyWithSender requires stream=true") + } + reqBody["stream"] = true🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/entity/models/zhipu-ai.go` around lines 203 - 205, The ChatStreamlyWithSender SSE-only handler can receive non-streaming responses because chatModelConfig.Stream may be nil or false; in ChatStreamlyWithSender ensure the outgoing request explicitly forces streaming by setting reqBody["stream"] = true (overriding any existing chatModelConfig.Stream) so the server always returns SSE; update the code path that builds reqBody (referencing chatModelConfig.Stream and reqBody["stream"]) to unconditionally set the stream flag to true before sending.
78-80:⚠️ Potential issue | 🟠 MajorPrevent
Chatfrom requesting streaming responses.
Chatreads the body as one JSON document; ifstream=trueis passed here, the API returns SSE andjson.Unmarshalfails. This was already flagged previously and still applies.Suggested fix
- if chatModelConfig.Stream != nil { - reqBody["stream"] = *chatModelConfig.Stream - } + if chatModelConfig.Stream != nil && *chatModelConfig.Stream { + return nil, fmt.Errorf("Chat does not support stream=true; use ChatStreamlyWithSender") + } + reqBody["stream"] = false🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/entity/models/zhipu-ai.go` around lines 78 - 80, The code currently adds chatModelConfig.Stream into reqBody which causes the Chat path to request SSE (stream=true) and break json.Unmarshal; update the request-building logic in the Chat-related function in zhipu-ai.go so that reqBody["stream"] is NOT set for Chat requests: remove the unconditional block that sets reqBody["stream"] using chatModelConfig.Stream, or add a guard that only sets stream for non-Chat endpoints; refer to the Chat handler and the chatModelConfig/reqBody variables to locate and change the logic.
🤖 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/deepseek.go`:
- Around line 96-118: In ListModels, validate the APIConfig and its fields
before building the request: check that apiConfig is non-nil, that
apiConfig.ApiKey is non-nil (return an error instead of dereferencing
*apiConfig.ApiKey), and resolve the region safely by using apiConfig.Region if
provided but verifying that z.BaseURL contains that key (otherwise return an
explicit error about unknown region or fall back to "default" only if
z.BaseURL["default"] exists); also ensure z.URLSuffix.Models is present before
composing the URL to avoid producing malformed URLs from empty map lookups.
- Around line 52-65: The PR exposes DeepSeek via the factory but DeepSeekModel's
core methods Chat, ChatStreamlyWithSender, and EncodeToEmbedding are stubs
returning "not implemented", which will cause runtime failures; either implement
these methods in DeepSeekModel to perform chat, streaming and embedding behavior
(respectively: DeepSeekModel.Chat, DeepSeekModel.ChatStreamlyWithSender,
DeepSeekModel.EncodeToEmbedding) using the provider's API and matching existing
ChatConfig/EmbeddingConfig handling, or revert the factory registration so
factory.go does not return DeepSeekModel for the "deepseek" key and instead
keeps it routed to the fallback driver until the implementations are complete.
Ensure whichever path you choose, factory.go and DeepSeekModel remain consistent
(no factory exposure of unimplemented driver).
In `@internal/entity/models/factory.go`:
- Around line 38-41: The factory currently returns NewDeepSeekModel and
NewMooshotModel from the "deepseek" and "moonshot" cases even though those
implementations only support listing and leave chat/stream/embedding
unimplemented; update the switch in factory.go so the factory does not route
full provider traffic to these partial drivers: either remove/guard the
"deepseek" and "moonshot" cases to return an explicit error (e.g., "driver not
implemented") or route them to the complete DeepSeek/Moonshot driver
implementations instead; reference the NewDeepSeekModel and NewMooshotModel
constructors and ensure any change prevents the factory from handing out a
partially-implemented model until chat/stream/embedding are implemented.
In `@internal/entity/models/moonshot.go`:
- Around line 67-118: The ListModels method in MooshotModel must be rewritten:
stop using POST with an empty JSON body — use GET to the URL built from
z.BaseURL[region] and z.URLSuffix.Models and remove the request body; add a nil
check for apiConfig.ApiKey before dereferencing to avoid a panic; replace the
generic map[string]interface{} + impossible []string assertion with a typed
response struct matching Moonshot’s schema (e.g., struct { Object string
`json:"object"`; Data []struct { ID string `json:"id"` } `json:"data"` }) and
iterate over Data to collect IDs; follow the pattern used in
DeepSeekModel.ListModels (deepseek.go) for request creation, response
unmarshalling, status handling, and extracting model IDs.
- Around line 29-36: The struct and constructor are misspelled as MooshotModel
and NewMooshotModel; rename them to MoonshotModel and NewMoonshotModel (and
update any file-level doc/comments) so they match the provider name; also update
all method receivers that reference MooshotModel (the four methods defined
below) to use MoonshotModel, and change the factory dispatch call in factory.go
that registers/constructs this type to use NewMoonshotModel/MoonshotModel so
grepping and wiring for "moonshot" remain consistent.
In `@internal/entity/models/types.go`:
- Around line 15-18: The ChatResponse struct's ReasonContent field uses the
wrong JSON tag; update the struct definition (ChatResponse and its ReasonContent
field) to use `reasoning_content` as the json tag instead of `reason_content` so
marshaling matches the rest of the PR and the new response contract.
In `@internal/handler/providers.go`:
- Around line 697-701: The handler currently returns "reasoning_content" and
"answer" at the top level in the c.JSON call; wrap those into a "data" object so
the non-stream chat payload matches the CLI expectation (resJSON["data"]).
Update the c.JSON response that references response.ReasonContent and
response.Answer to return a JSON body with "code": 0 and a "data" field
containing "reasoning_content": response.ReasonContent and "answer":
response.Answer (keep any other existing top-level keys intact).
---
Duplicate comments:
In `@internal/entity/models/zhipu-ai.go`:
- Around line 203-205: The ChatStreamlyWithSender SSE-only handler can receive
non-streaming responses because chatModelConfig.Stream may be nil or false; in
ChatStreamlyWithSender ensure the outgoing request explicitly forces streaming
by setting reqBody["stream"] = true (overriding any existing
chatModelConfig.Stream) so the server always returns SSE; update the code path
that builds reqBody (referencing chatModelConfig.Stream and reqBody["stream"])
to unconditionally set the stream flag to true before sending.
- Around line 78-80: The code currently adds chatModelConfig.Stream into reqBody
which causes the Chat path to request SSE (stream=true) and break
json.Unmarshal; update the request-building logic in the Chat-related function
in zhipu-ai.go so that reqBody["stream"] is NOT set for Chat requests: remove
the unconditional block that sets reqBody["stream"] using
chatModelConfig.Stream, or add a guard that only sets stream for non-Chat
endpoints; refer to the Chat handler and the chatModelConfig/reqBody variables
to locate and change the logic.
🪄 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: 485bc181-9558-4ae5-800d-30d67013cc55
📒 Files selected for processing (14)
internal/cli/client.gointernal/cli/common_command.gointernal/cli/lexer.gointernal/cli/types.gointernal/cli/user_parser.gointernal/entity/model.gointernal/entity/models/deepseek.gointernal/entity/models/dummy.gointernal/entity/models/factory.gointernal/entity/models/moonshot.gointernal/entity/models/types.gointernal/entity/models/zhipu-ai.gointernal/handler/providers.gointernal/service/model_service.go
🚧 Files skipped from review as they are similar to previous changes (4)
- internal/cli/lexer.go
- internal/entity/model.go
- internal/entity/models/dummy.go
- internal/service/model_service.go
| // Chat sends a message and returns response | ||
| func (z *DeepSeekModel) Chat(modelName, message *string, apiConfig *APIConfig, chatModelConfig *ChatConfig) (*ChatResponse, error) { | ||
| return nil, fmt.Errorf("not implemented") | ||
| } | ||
|
|
||
| // ChatStreamlyWithSender sends a message and streams response via sender function (best performance, no channel) | ||
| func (z *DeepSeekModel) ChatStreamlyWithSender(modelName, message *string, apiConfig *APIConfig, chatModelConfig *ChatConfig, sender func(*string, *string) error) error { | ||
| return fmt.Errorf("not implemented") | ||
| } | ||
|
|
||
| // EncodeToEmbedding encodes a list of texts into embeddings | ||
| func (z *DeepSeekModel) EncodeToEmbedding(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([][]float64, error) { | ||
| return nil, fmt.Errorf("not implemented") | ||
| } |
There was a problem hiding this comment.
Don’t expose DeepSeek through the factory while core methods are stubs.
factory.go now returns DeepSeekModel for deepseek, so chat/stream/embedding requests for that provider will fail at runtime with not implemented.
Suggested options
func (z *DeepSeekModel) Chat(modelName, message *string, apiConfig *APIConfig, chatModelConfig *ChatConfig) (*ChatResponse, error) {
- return nil, fmt.Errorf("not implemented")
+ return nil, fmt.Errorf("deepseek chat is not implemented")
}Prefer implementing these methods before registering the driver, or keep DeepSeek on the existing fallback driver until only ListModels is routed through a capability-specific path.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/models/deepseek.go` around lines 52 - 65, The PR exposes
DeepSeek via the factory but DeepSeekModel's core methods Chat,
ChatStreamlyWithSender, and EncodeToEmbedding are stubs returning "not
implemented", which will cause runtime failures; either implement these methods
in DeepSeekModel to perform chat, streaming and embedding behavior
(respectively: DeepSeekModel.Chat, DeepSeekModel.ChatStreamlyWithSender,
DeepSeekModel.EncodeToEmbedding) using the provider's API and matching existing
ChatConfig/EmbeddingConfig handling, or revert the factory registration so
factory.go does not return DeepSeekModel for the "deepseek" key and instead
keeps it routed to the fallback driver until the implementations are complete.
Ensure whichever path you choose, factory.go and DeepSeekModel remain consistent
(no factory exposure of unimplemented driver).
| func (z *DeepSeekModel) ListModels(apiConfig *APIConfig) ([]string, error) { | ||
| var region = "default" | ||
| if apiConfig.Region != nil { | ||
| region = *apiConfig.Region | ||
| } | ||
|
|
||
| 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)) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to create request: %w", err) | ||
| } | ||
|
|
||
| req.Header.Set("Content-Type", "application/json") | ||
| req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) |
There was a problem hiding this comment.
Validate API config and region before building the request.
apiConfig.Region and *apiConfig.ApiKey can panic when nil, and z.BaseURL[region] silently returns "" for unknown regions, producing malformed URLs.
Suggested fix
func (z *DeepSeekModel) ListModels(apiConfig *APIConfig) ([]string, error) {
+ if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
+ return nil, fmt.Errorf("missing API key")
+ }
+
var region = "default"
if apiConfig.Region != nil {
region = *apiConfig.Region
}
- url := fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.Models)
+ baseURL, ok := z.BaseURL[region]
+ if !ok || baseURL == "" {
+ return nil, fmt.Errorf("region %q not found in BaseURL configuration", region)
+ }
+
+ url := fmt.Sprintf("%s/%s", baseURL, z.URLSuffix.Models)📝 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 *DeepSeekModel) ListModels(apiConfig *APIConfig) ([]string, error) { | |
| var region = "default" | |
| if apiConfig.Region != nil { | |
| region = *apiConfig.Region | |
| } | |
| 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)) | |
| if err != nil { | |
| return nil, fmt.Errorf("failed to create request: %w", err) | |
| } | |
| req.Header.Set("Content-Type", "application/json") | |
| req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) | |
| func (z *DeepSeekModel) ListModels(apiConfig *APIConfig) ([]string, error) { | |
| if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" { | |
| return nil, fmt.Errorf("missing API key") | |
| } | |
| var region = "default" | |
| if apiConfig.Region != nil { | |
| region = *apiConfig.Region | |
| } | |
| baseURL, ok := z.BaseURL[region] | |
| if !ok || baseURL == "" { | |
| return nil, fmt.Errorf("region %q not found in BaseURL configuration", region) | |
| } | |
| url := fmt.Sprintf("%s/%s", baseURL, 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)) | |
| if err != nil { | |
| return nil, fmt.Errorf("failed to create request: %w", err) | |
| } | |
| req.Header.Set("Content-Type", "application/json") | |
| 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/deepseek.go` around lines 96 - 118, In ListModels,
validate the APIConfig and its fields before building the request: check that
apiConfig is non-nil, that apiConfig.ApiKey is non-nil (return an error instead
of dereferencing *apiConfig.ApiKey), and resolve the region safely by using
apiConfig.Region if provided but verifying that z.BaseURL contains that key
(otherwise return an explicit error about unknown region or fall back to
"default" only if z.BaseURL["default"] exists); also ensure z.URLSuffix.Models
is present before composing the URL to avoid producing malformed URLs from empty
map lookups.
| case "deepseek": | ||
| return NewDeepSeekModel(baseURL, urlSuffix), nil | ||
| case "moonshot": | ||
| return NewMooshotModel(baseURL, urlSuffix), nil |
There was a problem hiding this comment.
Avoid routing full provider traffic to partial drivers.
Both newly registered drivers only implement model listing per the provided snippets; their chat/stream/embedding methods return not implemented. Once the factory selects these drivers, normal DeepSeek/Moonshot chat flows regress at runtime.
Suggested guard until the drivers are complete
- case "deepseek":
- return NewDeepSeekModel(baseURL, urlSuffix), nil
- case "moonshot":
- return NewMooshotModel(baseURL, urlSuffix), nilAlternatively, keep these cases and implement the missing chat/stream/embedding methods before merge.
📝 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.
| case "deepseek": | |
| return NewDeepSeekModel(baseURL, urlSuffix), nil | |
| case "moonshot": | |
| return NewMooshotModel(baseURL, urlSuffix), nil |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/models/factory.go` around lines 38 - 41, The factory
currently returns NewDeepSeekModel and NewMooshotModel from the "deepseek" and
"moonshot" cases even though those implementations only support listing and
leave chat/stream/embedding unimplemented; update the switch in factory.go so
the factory does not route full provider traffic to these partial drivers:
either remove/guard the "deepseek" and "moonshot" cases to return an explicit
error (e.g., "driver not implemented") or route them to the complete
DeepSeek/Moonshot driver implementations instead; reference the NewDeepSeekModel
and NewMooshotModel constructors and ensure any change prevents the factory from
handing out a partially-implemented model until chat/stream/embedding are
implemented.
| type MooshotModel struct { | ||
| BaseURL map[string]string | ||
| URLSuffix URLSuffix | ||
| httpClient *http.Client // Reusable HTTP client with connection pool | ||
| } | ||
|
|
||
| // NewMooshotModel creates a new Mooshot model instance | ||
| func NewMooshotModel(baseURL map[string]string, urlSuffix URLSuffix) *MooshotModel { |
There was a problem hiding this comment.
Spelling: Mooshot → Moonshot.
The struct/constructor/comment say Mooshot (missing an n), but the provider name is Moonshot (AI team / api.moonshot.ai). The factory dispatches "moonshot" to this type, so rename to MoonshotModel / NewMoonshotModel for consistency and greppability, and update the receiver names / file-level doc.
📝 Proposed rename
-// MooshotModel implements ModelDriver for Mooshot
-type MooshotModel struct {
+// MoonshotModel implements ModelDriver for Moonshot
+type MoonshotModel struct {
BaseURL map[string]string
URLSuffix URLSuffix
httpClient *http.Client // Reusable HTTP client with connection pool
}
-// NewMooshotModel creates a new Mooshot model instance
-func NewMooshotModel(baseURL map[string]string, urlSuffix URLSuffix) *MooshotModel {
- return &MooshotModel{
+// NewMoonshotModel creates a new Moonshot model instance
+func NewMoonshotModel(baseURL map[string]string, urlSuffix URLSuffix) *MoonshotModel {
+ return &MoonshotModel{(also update the four method receivers below and the factory callsite in internal/entity/models/factory.go)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/models/moonshot.go` around lines 29 - 36, The struct and
constructor are misspelled as MooshotModel and NewMooshotModel; rename them to
MoonshotModel and NewMoonshotModel (and update any file-level doc/comments) so
they match the provider name; also update all method receivers that reference
MooshotModel (the four methods defined below) to use MoonshotModel, and change
the factory dispatch call in factory.go that registers/constructs this type to
use NewMoonshotModel/MoonshotModel so grepping and wiring for "moonshot" remain
consistent.
| func (z *MooshotModel) ListModels(apiConfig *APIConfig) ([]string, error) { | ||
| var region = "default" | ||
| if apiConfig.Region != nil { | ||
| region = *apiConfig.Region | ||
| } | ||
|
|
||
| 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("POST", url, bytes.NewBuffer(jsonData)) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to create request: %w", err) | ||
| } | ||
|
|
||
| req.Header.Set("Content-Type", "application/json") | ||
| req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) | ||
|
|
||
| resp, err := z.httpClient.Do(req) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to send request: %w", err) | ||
| } | ||
| defer resp.Body.Close() | ||
|
|
||
| body, err := io.ReadAll(resp.Body) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to read response: %w", err) | ||
| } | ||
|
|
||
| if resp.StatusCode != http.StatusOK { | ||
| return nil, fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body)) | ||
| } | ||
|
|
||
| // 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) | ||
| } | ||
|
|
||
| models, ok := result["models"].([]string) | ||
| if !ok || len(models) == 0 { | ||
| return nil, fmt.Errorf("no models in response") | ||
| } | ||
|
|
||
| return models, nil | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Inspect how URLSuffix.Models is configured for moonshot and how other drivers implement ListModels
rg -nP --type=go -C3 '\bURLSuffix\b|\bModels\s*:'
rg -nP --type=go -C3 'NewMooshotModel|NewMoonshotModel|"moonshot"'
# Compare with an existing working driver's ListModels for the expected response schema
ast-grep --pattern $'func ($_ $_) ListModels(apiConfig *APIConfig) ([]string, error) {
$$$
}'Repository: infiniflow/ragflow
Length of output: 17460
🌐 Web query:
Does the Moonshot (Kimi) Open Platform /v1/models endpoint use GET and return {"data":[{"id":...}]} like OpenAI?
💡 Result:
Yes, the Moonshot (Kimi) Open Platform /v1/models endpoint uses GET and returns {"data":[{"id":...}]} like OpenAI.
Citations:
- 1: https://platform.moonshot.ai/docs/api-reference
- 2: https://platform.kimi.ai/docs/api/overview
🏁 Script executed:
rg -A 10 'type URLSuffix struct' internal/entity/models/Repository: infiniflow/ragflow
Length of output: 729
ListModels is broken end-to-end: wrong HTTP verb, wrong response schema, and an impossible type assertion.
This method cannot function against the Moonshot API as written. Four compounding defects prevent it from ever returning models successfully:
-
Type assertion always fails (line 112).
json.Unmarshalintomap[string]interface{}decodes JSON arrays as[]interface{}, never[]string. The assertionresult["models"].([]string)will always fail and return"no models in response"even for correct server responses. Decode into a typed struct instead. -
Wrong HTTP method (line 83). Moonshot's OpenAI-compatible API uses
GETon/v1/models, notPOST. Remove the request body and empty JSON marshaling. -
Wrong response schema (line 112). Moonshot returns
{"object":"list","data":[{"id":"kimi-...", ...}, ...]}, not a top-levelmodelskey. Extract model IDs from thedataarray. -
Nil-pointer deref on
*apiConfig.ApiKey(line 89). Add a nil check before dereferencing to avoid panicking on misconfigured instances.
See the DeepSeekModel.ListModels implementation (deepseek.go:96–147) for the correct pattern: GET request, typed struct unmarshaling, and extracting IDs from the response.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/models/moonshot.go` around lines 67 - 118, The ListModels
method in MooshotModel must be rewritten: stop using POST with an empty JSON
body — use GET to the URL built from z.BaseURL[region] and z.URLSuffix.Models
and remove the request body; add a nil check for apiConfig.ApiKey before
dereferencing to avoid a panic; replace the generic map[string]interface{} +
impossible []string assertion with a typed response struct matching Moonshot’s
schema (e.g., struct { Object string `json:"object"`; Data []struct { ID string
`json:"id"` } `json:"data"` }) and iterate over Data to collect IDs; follow the
pattern used in DeepSeekModel.ListModels (deepseek.go) for request creation,
response unmarshalling, status handling, and extracting model IDs.
| type ChatResponse struct { | ||
| Answer *string `json:"answer"` | ||
| ReasonContent *string `json:"reason_content"` | ||
| } |
There was a problem hiding this comment.
Align the JSON tag with the new response contract.
The rest of the PR uses reasoning_content, but this struct tag emits reason_content if ChatResponse is marshaled directly.
Suggested fix
type ChatResponse struct {
Answer *string `json:"answer"`
- ReasonContent *string `json:"reason_content"`
+ ReasonContent *string `json:"reasoning_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.
| type ChatResponse struct { | |
| Answer *string `json:"answer"` | |
| ReasonContent *string `json:"reason_content"` | |
| } | |
| type ChatResponse struct { | |
| Answer *string `json:"answer"` | |
| ReasonContent *string `json:"reasoning_content"` | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/models/types.go` around lines 15 - 18, The ChatResponse
struct's ReasonContent field uses the wrong JSON tag; update the struct
definition (ChatResponse and its ReasonContent field) to use `reasoning_content`
as the json tag instead of `reason_content` so marshaling matches the rest of
the PR and the new response contract.
| c.JSON(http.StatusOK, gin.H{ | ||
| "code": 0, | ||
| "message": response, | ||
| "code": 0, | ||
| "reasoning_content": response.ReasonContent, | ||
| "answer": response.Answer, | ||
| }) |
There was a problem hiding this comment.
Keep the non-stream chat payload under data.
The CLI paths in internal/cli/user_command.go still read resJSON["data"], so returning answer and reasoning_content at the top level makes non-stream chat responses fail client-side parsing.
Suggested fix
c.JSON(http.StatusOK, gin.H{
- "code": 0,
- "reasoning_content": response.ReasonContent,
- "answer": response.Answer,
+ "code": 0,
+ "message": "success",
+ "data": gin.H{
+ "reasoning_content": response.ReasonContent,
+ "answer": response.Answer,
+ },
})📝 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.
| c.JSON(http.StatusOK, gin.H{ | |
| "code": 0, | |
| "message": response, | |
| "code": 0, | |
| "reasoning_content": response.ReasonContent, | |
| "answer": response.Answer, | |
| }) | |
| c.JSON(http.StatusOK, gin.H{ | |
| "code": 0, | |
| "message": "success", | |
| "data": gin.H{ | |
| "reasoning_content": response.ReasonContent, | |
| "answer": response.Answer, | |
| }, | |
| }) |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/handler/providers.go` around lines 697 - 701, The handler currently
returns "reasoning_content" and "answer" at the top level in the c.JSON call;
wrap those into a "data" object so the non-stream chat payload matches the CLI
expectation (resJSON["data"]). Update the c.JSON response that references
response.ReasonContent and response.Answer to return a JSON body with "code": 0
and a "data" field containing "reasoning_content": response.ReasonContent and
"answer": response.Answer (keep any other existing top-level keys intact).
### What problem does this PR solve? 1. Supports stream and non-stream chat 2. Supports think and non-think chat 3. List supported models from DeepSeek service. (This command can be used to verify the API validity) ### 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?
Type of change