Skip to content

Go: add stream / think chat - #14242

Merged
JinHai-CN merged 8 commits into
infiniflow:mainfrom
JinHai-CN:fix393
Apr 21, 2026
Merged

JinHai-CN merged 8 commits into
infiniflow:mainfrom
JinHai-CN:fix393

Conversation

@JinHai-CN

@JinHai-CN JinHai-CN commented Apr 21, 2026 •

Copy link
Copy Markdown
Member

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

  • New Feature (non-breaking change which adds functionality)

@coderabbitai

coderabbitai Bot commented Apr 21, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Lexer 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

Cohort / File(s) Summary
Lexer & Tokens
internal/cli/types.go, internal/cli/lexer.go
Inserted TokenSupported and TokenStream, removed TokenDocMeta; lexer now recognizes STREAM and SUPPORTED.
Parser & CLI parsing
internal/cli/parser.go, internal/cli/user_parser.go
Parser dispatch for TokenStream; added parseStreamCommand; parseListCommand handles TokenSupported; chat/think parsing use thinking and stream params.
CLI command handling & client
internal/cli/user_command.go, internal/cli/client.go, internal/cli/common_command.go
ChatToModel reads thinking and stream; streams via SSE when stream=true, otherwise POSTs and decodes NonStreamResponse; added client routing and ListSupportedModels client command.
Response model & printing
internal/cli/response.go
Replaced MessageResponse with NonStreamResponse; success payload split into reasoning_content and answer; print logic adjusted.
Handler & request shapes
internal/handler/providers.go
Request field reasoning → thinking; handler supports supported=true param to return supported models; non-stream response body changed to reasoning_content + answer.
Service layer
internal/service/model_service.go
Added ListSupportedModels; ChatToModel/stream variants now accept apiConfig *APIConfig and return *ChatResponse / use apiConfig derived from instance extra/API key.
Model interface & types
internal/entity/models/types.go, internal/entity/models/dummy.go
ModelDriver signatures updated to accept apiConfig *APIConfig; Chat returns *ChatResponse; added ListModels; ChatConfig.Reasoning → Thinking; new APIConfig, ChatResponse, adjusted embedding config.
Model implementations & factory
internal/entity/models/zhipu-ai.go, internal/entity/models/deepseek.go, internal/entity/models/moonshot.go, internal/entity/models/factory.go
Zhipu-ai updated for apiConfig, region-aware baseURL, returns ChatResponse; added DeepSeek and Mooshot model drivers with ListModels; factory recognizes deepseek and moonshot.
Model feature config & model init
conf/models/zhipu-ai.json, internal/entity/model.go
Removed clear, added clear_thinking feature; model init reads ClearThinking.SupportedModels and sets Thinking.ClearContent per model prefixes.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

🐇
I sniffed a STREAM and hopped with glee,
Tokens, thoughts, and answers split for me,
Models now speak in region and key,
A rabbit cheers: print thinking, then reply —
Hop on, stream on, code runs merrily!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Go: add stream / think chat' clearly describes the main feature additions in this changeset: support for stream/non-stream and think/non-think chat modes.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description check ✅ Passed The PR description addresses the stated objectives and provides essential context, though it lacks background and detailed problem context.

✏️ 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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@JinHai-CN JinHai-CN added the ci Continue Integration label Apr 21, 2026
@JinHai-CN
JinHai-CN marked this pull request as ready for review April 21, 2026 04:19
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Apr 21, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_content differs from reasoning_content used in internal/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 returning nil for ReasonContent when thinking is disabled.

When Thinking is false or nil, ReasonContent is set to a pointer to an empty string rather than nil. Consumers (like the CLI at response.go:139) check for empty string, but semantically nil better 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

📥 Commits

Reviewing files that changed from the base of the PR and between b3891ba and af158f6.

📒 Files selected for processing (11)
  • internal/cli/lexer.go
  • internal/cli/parser.go
  • internal/cli/response.go
  • internal/cli/types.go
  • internal/cli/user_command.go
  • internal/cli/user_parser.go
  • internal/entity/models/dummy.go
  • internal/entity/models/types.go
  • internal/entity/models/zhipu-ai.go
  • internal/handler/providers.go
  • internal/service/model_service.go

Comment on lines 1438 to +1440
message := cmd.Params["message"].(string)
reasoning := cmd.Params["reasoning"].(bool)
thinking := cmd.Params["thinking"].(bool)
stream := cmd.Params["stream"].(bool)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

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.

Suggested change
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).

Comment on lines +1470 to +1493
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)
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

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.

Suggested change
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.

Comment on lines +1520 to +1531
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

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.

Suggested change
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.

Comment on lines +2218 to 2239
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
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

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.

Suggested change
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.

Comment on lines +61 to +66
var region = "default"
if chatModelConfig.Region != nil {
region = *chatModelConfig.Region
}

url := fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.Chat)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

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.

Suggested change
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.

Comment thread internal/entity/models/zhipu-ai.go Resolved
@codecov

codecov Bot commented Apr 21, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 96.66%. Comparing base (8aab158) to head (2927be8).
⚠️ Report is 7 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

♻️ Duplicate comments (1)
internal/entity/models/zhipu-ai.go (1)

61-66: ⚠️ Potential issue | 🟡 Minor

Validate 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

📥 Commits

Reviewing files that changed from the base of the PR and between af158f6 and 4e72ea2.

📒 Files selected for processing (1)
  • internal/entity/models/zhipu-ai.go

Comment on lines +78 to +80
if chatModelConfig.Stream != nil {
reqBody["stream"] = *chatModelConfig.Stream
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

cd internal/entity/models && wc -l zhipu-ai.go

Repository: infiniflow/ragflow

Length of output: 77


🏁 Script executed:

cat -n internal/entity/models/zhipu-ai.go | head -150

Repository: 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.

Comment on lines +203 to +205
if chatModelConfig.Stream != nil {
reqBody["stream"] = *chatModelConfig.Stream
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

find . -name "zhipu-ai.go" -type f

Repository: 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 5

Repository: 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 -120

Repository: 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 3

Repository: infiniflow/ragflow

Length of output: 503


🏁 Script executed:

rg "ChatStreamlyWithSender" -g "*.go" -B 3 -A 3

Repository: infiniflow/ragflow

Length of output: 2666


🏁 Script executed:

rg "ChatConfig" internal/entity/models/ -g "*.go" -B 2 -A 10 | head -80

Repository: 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.

Suggested change
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.

@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Apr 21, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4e72ea2 and 86235b7.

📒 Files selected for processing (2)
  • conf/models/zhipu-ai.json
  • internal/entity/model.go

Comment thread internal/entity/model.go Outdated
Features Features `json:"features"`
ModelDriver models.ModelDriver
Name string `json:"name"`
URL map[string]string `json:"url"`

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 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.go

Repository: 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 -20

Repository: 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 -5

Repository: 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.go

Repository: 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 -50

Repository: infiniflow/ragflow

Length of output: 930


🏁 Script executed:

cat conf/models/xai.json | head -50

Repository: 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.json

Repository: 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.

Comment thread internal/entity/model.go Resolved
@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:XXL This PR changes 1000+ lines, ignoring generated files. labels Apr 21, 2026
Signed-off-by: Jin Hai <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

♻️ Duplicate comments (2)
internal/entity/models/zhipu-ai.go (2)

203-205: ⚠️ Potential issue | 🟠 Major

Force streaming mode for ChatStreamlyWithSender.

This method only parses SSE, but the request can still be sent with stream=false or 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 | 🟠 Major

Prevent Chat from requesting streaming responses.

Chat reads the body as one JSON document; if stream=true is passed here, the API returns SSE and json.Unmarshal fails. 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

📥 Commits

Reviewing files that changed from the base of the PR and between 86235b7 and 2927be8.

📒 Files selected for processing (14)
  • internal/cli/client.go
  • internal/cli/common_command.go
  • internal/cli/lexer.go
  • internal/cli/types.go
  • internal/cli/user_parser.go
  • internal/entity/model.go
  • internal/entity/models/deepseek.go
  • internal/entity/models/dummy.go
  • internal/entity/models/factory.go
  • internal/entity/models/moonshot.go
  • internal/entity/models/types.go
  • internal/entity/models/zhipu-ai.go
  • internal/handler/providers.go
  • internal/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

Comment on lines +52 to +65
// 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")
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

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).

Comment on lines +96 to +118
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))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

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.

Suggested change
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.

Comment on lines +38 to +41
case "deepseek":
return NewDeepSeekModel(baseURL, urlSuffix), nil
case "moonshot":
return NewMooshotModel(baseURL, urlSuffix), nil

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

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), nil

Alternatively, 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.

Suggested change
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.

Comment on lines +29 to +36
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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

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.

Comment on lines +67 to +118
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
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 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:


🏁 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:

  1. Type assertion always fails (line 112). json.Unmarshal into map[string]interface{} decodes JSON arrays as []interface{}, never []string. The assertion result["models"].([]string) will always fail and return "no models in response" even for correct server responses. Decode into a typed struct instead.

  2. Wrong HTTP method (line 83). Moonshot's OpenAI-compatible API uses GET on /v1/models, not POST. Remove the request body and empty JSON marshaling.

  3. Wrong response schema (line 112). Moonshot returns {"object":"list","data":[{"id":"kimi-...", ...}, ...]}, not a top-level models key. Extract model IDs from the data array.

  4. 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.

Comment on lines +15 to 18
type ChatResponse struct {
Answer *string `json:"answer"`
ReasonContent *string `json:"reason_content"`
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

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.

Suggested change
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.

Comment on lines 697 to 701
c.JSON(http.StatusOK, gin.H{
"code": 0,
"message": response,
"code": 0,
"reasoning_content": response.ReasonContent,
"answer": response.Answer,
})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

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.

Suggested change
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).

@JinHai-CN
JinHai-CN merged commit e48d759 into infiniflow:main Apr 21, 2026
1 check passed
JasleenKaurSethi pushed a commit to stackhpc/ragflow that referenced this pull request Apr 28, 2026
### 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant