Repository navigation
Go: implement provider: MiniMax - #14478
Conversation
📝 WalkthroughWalkthroughThe changes add Minimax API integration support by introducing configuration for a models endpoint and implementing three core HTTP methods (Chat, ChatStreamlyWithSender, ListModels). Configuration extends chat models with thinking capability settings. A streaming logic fix in Volcengine prevents invalid content forwarding. Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~22 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 inconclusive)
✅ Passed checks (4 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. Review rate limit: 7/8 reviews remaining, refill in 7 minutes and 30 seconds.Comment |
There was a problem hiding this comment.
Actionable comments posted: 6
🤖 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/minimax.go`:
- Around line 161-166: The sync path currently treats
messageMap["reasoning_content"] as required when modelConfig.Thinking is true
and returns an error if it's missing; change this to make reasoning_content
optional like the streaming path by not returning an error when the
type/assertion fails — instead set reasonContent to an empty string (or leave it
unset) and continue processing. Update the code around reasonContent, the
modelConfig.Thinking check, and the messageMap["reasoning_content"] type
assertion so a missing or non-string reasoning_content does not abort the
request.
- Around line 261-263: The code currently logs raw MiniMax stream chunks via
scanner.Text() using logger.Info(line); remove that info-level logging to avoid
writing user-visible/model reasoning content to logs, or change it to debug-only
and redact sensitive portions before logging (e.g., replace full content with a
length/placeholder or mask reasoning segments). Locate the scanner.Text() call
and the logger.Info(line) invocation in minimax.go and either delete the
logger.Info call or wrap it with a debug-level guard and apply a redaction
function before passing text to the logger.
- Around line 141-149: The parsing code in internal/entity/models/minimax.go
(e.g., the block using result["choices"] and accessing choices[0]) can panic
when arrays are empty or payload shapes differ; add defensive checks: verify
choices is a non-nil slice and len(choices) > 0 before indexing, and replace
unsafe type assertions with guarded conversions that return a descriptive error
if a field is missing or of the wrong type. Do the same hardening for the
ListModels path (the data[] / id extraction around the 377-382 area): check that
data is a slice, each element is a map[string]interface{}, and that id exists as
a string before using it, returning an error instead of panicking. Ensure all
new errors include context about which field is missing/invalid and reference
the functions handling the response so callers can trace failures.
- Around line 91-93: The code currently lets callers override the wire "stream"
mode by copying modelConfig.Stream into reqBody["stream"]; for methods Chat
(non-streaming) and ChatStreamlyWithSender (streaming) you must keep the wire
mode fixed per method or reject conflicting values: in Chat and the
non-streaming variants ignore modelConfig.Stream or, better, if
modelConfig.Stream is non-nil and its value conflicts with the method's fixed
mode return an error; in ChatStreamlyWithSender always set reqBody["stream"] =
true (and reject modelConfig.Stream==false) and in the non-streaming Chat always
set reqBody["stream"] = false (and reject modelConfig.Stream==true). Apply the
same fix for the other occurrence around the 206-208 block so callers cannot
flip the wire mode via modelConfig.Stream.
- Around line 67-72: Normalize apiConfig.Region before building URLs: if
apiConfig.Region is nil or *apiConfig.Region == "" set region to the service
default (use the resolver/default field you have on z, e.g., z.defaultRegion or
z.DefaultRegion); then validate that region exists in z.BaseURL (if _, ok :=
z.BaseURL[region]; !ok return/fail fast with a clear error). Apply this pattern
in the Chat method where z.URLSuffix.Chat is used and the two other methods
referenced (the blocks at lines ~188-195 and ~333-339) so nil/empty regions are
defaulted and missing region keys cause early errors instead of panics or using
z.BaseURL[""].
- Around line 318-324: The code currently sends the end-of-stream marker
(endOfStream := "[DONE]"; sender(&endOfStream, nil)) before checking
scanner.Err(), which can signal completion even when the stream errored; update
the logic in the streaming/flush path (where sender and scanner.Err() are used)
to first check scanner.Err() and return that error if non-nil, and only after
confirming scanner.Err() == nil call sender(&endOfStream, nil) to emit the
"[DONE]" marker (ensure you return any sender error as before).
🪄 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: 6f3b0a1d-6e1f-4dd3-9b31-a782c00ac239
📒 Files selected for processing (3)
conf/models/minimax.jsoninternal/entity/models/minimax.gointernal/entity/models/volcengine.go
| if *apiConfig.Region != "" { | ||
| region = *apiConfig.Region | ||
| } | ||
|
|
||
| url := fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.Chat) | ||
|
|
There was a problem hiding this comment.
Normalize and validate region before building the URL.
Chat will panic when apiConfig.Region is nil, and the other two methods accept "" as a region and then build the request from z.BaseURL[""]. Please default on both nil and empty values, and fail fast if the resolved region is not present in BaseURL.
Also applies to: 188-195, 333-339
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/models/minimax.go` around lines 67 - 72, Normalize
apiConfig.Region before building URLs: if apiConfig.Region is nil or
*apiConfig.Region == "" set region to the service default (use the
resolver/default field you have on z, e.g., z.defaultRegion or z.DefaultRegion);
then validate that region exists in z.BaseURL (if _, ok := z.BaseURL[region];
!ok return/fail fast with a clear error). Apply this pattern in the Chat method
where z.URLSuffix.Chat is used and the two other methods referenced (the blocks
at lines ~188-195 and ~333-339) so nil/empty regions are defaulted and missing
region keys cause early errors instead of panics or using z.BaseURL[""].
| if modelConfig.Stream != nil { | ||
| reqBody["stream"] = *modelConfig.Stream | ||
| } |
There was a problem hiding this comment.
Do not let callers override the wire mode of these methods.
Chat can be switched into SSE mode, and ChatStreamlyWithSender can be switched back to a non-streaming response. In both cases the parser no longer matches the response format. Keep stream fixed per method or reject conflicting modelConfig.Stream values.
Also applies to: 206-208
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/models/minimax.go` around lines 91 - 93, The code currently
lets callers override the wire "stream" mode by copying modelConfig.Stream into
reqBody["stream"]; for methods Chat (non-streaming) and ChatStreamlyWithSender
(streaming) you must keep the wire mode fixed per method or reject conflicting
values: in Chat and the non-streaming variants ignore modelConfig.Stream or,
better, if modelConfig.Stream is non-nil and its value conflicts with the
method's fixed mode return an error; in ChatStreamlyWithSender always set
reqBody["stream"] = true (and reject modelConfig.Stream==false) and in the
non-streaming Chat always set reqBody["stream"] = false (and reject
modelConfig.Stream==true). Apply the same fix for the other occurrence around
the 206-208 block so callers cannot flip the wire mode via modelConfig.Stream.
| choices, ok := result["choices"].([]interface{}) | ||
| if !ok { | ||
| return nil, fmt.Errorf("no choices in response") | ||
| } | ||
|
|
||
| firstChoice, ok := choices[0].(map[string]interface{}) | ||
| if !ok { | ||
| return nil, fmt.Errorf("no choices in response") | ||
| } |
There was a problem hiding this comment.
Harden provider response parsing to avoid panics on unexpected payloads.
choices[0] is accessed without a length check, and ListModels uses unchecked type assertions all the way down to data[].id. A 200 response with an empty choices array or a different data shape will panic this provider instead of returning a normal error.
Also applies to: 377-382
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/models/minimax.go` around lines 141 - 149, The parsing code
in internal/entity/models/minimax.go (e.g., the block using result["choices"]
and accessing choices[0]) can panic when arrays are empty or payload shapes
differ; add defensive checks: verify choices is a non-nil slice and len(choices)
> 0 before indexing, and replace unsafe type assertions with guarded conversions
that return a descriptive error if a field is missing or of the wrong type. Do
the same hardening for the ListModels path (the data[] / id extraction around
the 377-382 area): check that data is a slice, each element is a
map[string]interface{}, and that id exists as a string before using it,
returning an error instead of panicking. Ensure all new errors include context
about which field is missing/invalid and reference the functions handling the
response so callers can trace failures.
| var reasonContent string | ||
| if modelConfig.Thinking != nil && *modelConfig.Thinking { | ||
| reasonContent, ok = messageMap["reasoning_content"].(string) | ||
| if !ok { | ||
| return nil, fmt.Errorf("invalid content format") | ||
| } |
There was a problem hiding this comment.
Treat reasoning_content as optional in the sync path.
When thinking is enabled, this currently fails the whole request if reasoning_content is absent, even when content is valid. The streaming path already treats that field as optional, so the sync path should do the same.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/models/minimax.go` around lines 161 - 166, The sync path
currently treats messageMap["reasoning_content"] as required when
modelConfig.Thinking is true and returns an error if it's missing; change this
to make reasoning_content optional like the streaming path by not returning an
error when the type/assertion fails — instead set reasonContent to an empty
string (or leave it unset) and continue processing. Update the code around
reasonContent, the modelConfig.Thinking check, and the
messageMap["reasoning_content"] type assertion so a missing or non-string
reasoning_content does not abort the request.
| line := scanner.Text() | ||
| logger.Info(line) | ||
|
|
There was a problem hiding this comment.
Remove info-level logging of raw MiniMax stream chunks.
These lines can include user-visible output and reasoning_content, so this is effectively logging model responses verbatim. Please drop it or gate a redacted version behind debug-only logging.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/models/minimax.go` around lines 261 - 263, The code currently
logs raw MiniMax stream chunks via scanner.Text() using logger.Info(line);
remove that info-level logging to avoid writing user-visible/model reasoning
content to logs, or change it to debug-only and redact sensitive portions before
logging (e.g., replace full content with a length/placeholder or mask reasoning
segments). Locate the scanner.Text() call and the logger.Info(line) invocation
in minimax.go and either delete the logger.Info call or wrap it with a
debug-level guard and apply a redaction function before passing text to the
logger.
| // Send [DONE] marker for OpenAI compatibility | ||
| endOfStream := "[DONE]" | ||
| if err = sender(&endOfStream, nil); err != nil { | ||
| return err | ||
| } | ||
|
|
||
| return scanner.Err() |
There was a problem hiding this comment.
Only emit "[DONE]" after confirming the stream ended cleanly.
Right now a scanner error still sends the completion marker first, which can make clients treat a truncated response as complete.
Suggested fix
- // Send [DONE] marker for OpenAI compatibility
- endOfStream := "[DONE]"
- if err = sender(&endOfStream, nil); err != nil {
- return err
- }
-
- return scanner.Err()
+ if err := scanner.Err(); err != nil {
+ return err
+ }
+
+ // Send [DONE] marker for OpenAI compatibility
+ endOfStream := "[DONE]"
+ return sender(&endOfStream, nil)📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| // Send [DONE] marker for OpenAI compatibility | |
| endOfStream := "[DONE]" | |
| if err = sender(&endOfStream, nil); err != nil { | |
| return err | |
| } | |
| return scanner.Err() | |
| if err := scanner.Err(); err != nil { | |
| return err | |
| } | |
| // Send [DONE] marker for OpenAI compatibility | |
| endOfStream := "[DONE]" | |
| return sender(&endOfStream, nil) |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/models/minimax.go` around lines 318 - 324, The code currently
sends the end-of-stream marker (endOfStream := "[DONE]"; sender(&endOfStream,
nil)) before checking scanner.Err(), which can signal completion even when the
stream errored; update the logic in the streaming/flush path (where sender and
scanner.Err() are used) to first check scanner.Err() and return that error if
non-nil, and only after confirming scanner.Err() == nil call
sender(&endOfStream, nil) to emit the "[DONE]" marker (ensure you return any
sender error as before).
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14478 +/- ##
=======================================
Coverage 95.30% 95.30%
=======================================
Files 10 10
Lines 703 703
Branches 112 112
=======================================
Hits 670 670
Misses 16 16
Partials 17 17 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
### What problem does this PR solve? implement MiniMax provider ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue) - [x] New Feature (non-breaking change which adds functionality)
Closes #14552 ### What problem does this PR solve? Add a Go driver for xAI (Grok models). The config file conf/models/xai.json has been in the repo since the early Go provider work, but internal/entity/models/factory.go had no case for "xai". So any xAI request fell through to the dummy driver and never reached the API. This PR adds the missing driver and wires it up. ### What this PR includes - New file internal/entity/models/xai.go with an XAIModel that implements the ModelDriver interface. - factory.go: route the "xai" provider name to NewXAIModel. ### How the driver works - xAI exposes an OpenAI-compatible API at https://api.x.ai/v1. - ChatWithMessages and ChatStreamlyWithSender post to /chat/completions in the same shape the moonshot and deepseek drivers use. - ListModels and CheckConnection call /models to confirm the API key works and to list available model ids. - reasoning_content is passed through for grok-3-mini and other xAI reasoning models, both in the non-stream and stream paths. - Encode, Rerank, and Balance are not part of the public xAI API at the moment, so they return a clear "not implemented" or "no such method" error. ### Type of change - [x] New Feature (non-breaking change which adds functionality) ### How was this tested? - go build ./internal/entity/models/... in a clean go 1.25 image (the go.mod minimum) returns exit 0 with no errors. - Method set of XAIModel matches the ModelDriver interface: NewInstance, Name, ChatWithMessages, ChatStreamlyWithSender, Encode, Rerank, ListModels, Balance, CheckConnection. - Pattern parity with the merged moonshot (#14433), volcengine (#14460), minimax (#14478), and vllm (#14532) PRs. --------- Co-authored-by: Jin Hai <[email protected]>
### What problem does this PR solve? Add a Go driver for OpenAI (GPT models). The config file conf/models/openai.json has been in the repo for a while with the full GPT-5 model list, but internal/entity/models/factory.go had no case for "openai". So any tenant that configured OpenAI as a model provider in the Go layer fell through to the default branch and got the dummy driver. Chat, list models, and check connection all returned dummy responses instead of reaching the API. OpenAI is the most commonly requested provider and the JSON config already ships with the repo, so this gap is high impact even though the JSON has been there for some time. ### What this PR includes - New file internal/entity/models/openai.go with an OpenAIModel that implements the ModelDriver interface. - factory.go: route the "openai" provider name to NewOpenAIModel. - conf/models/openai.json: add "models": "models" under url_suffix so ListModels can hit /v1/models with no hardcoded fallback. ### How the driver works - OpenAI exposes the canonical OpenAI-compatible API at https://api.openai.com/v1. - ChatWithMessages and ChatStreamlyWithSender post to /chat/completions in the same shape the moonshot, vllm, and xai drivers use. - ListModels and CheckConnection call /models to list available ids and confirm the API key works. - reasoning_content is passed through for the o-series and other reasoning models, in both the non-stream and stream paths. - Encode (embeddings) is left as "not implemented" for now, the same way the other recent provider drivers do it. Rerank and Balance are not part of OpenAI's public API surface in this layer and return a clear "not implemented" or "no such method" error. ### Type of change - [x] New Feature (non-breaking change which adds functionality) ### How was this tested? - go build ./internal/entity/models/... in a clean go 1.25 image (the go.mod minimum) returns exit 0 with no errors. - Method set of OpenAIModel matches the ModelDriver interface: NewInstance, Name, ChatWithMessages, ChatStreamlyWithSender, Encode, Rerank, ListModels, Balance, CheckConnection. - Pattern parity with the merged moonshot (#14433), volcengine (#14460), minimax (#14478), vllm (#14532), xai (#14550), and lm-studio (#14586) PRs. Closes #14604
### What problem does this PR solve? implement MiniMax provider ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue) - [x] New Feature (non-breaking change which adds functionality)
### What problem does this PR solve? Add a Go driver for OpenAI (GPT models). The config file conf/models/openai.json has been in the repo for a while with the full GPT-5 model list, but internal/entity/models/factory.go had no case for "openai". So any tenant that configured OpenAI as a model provider in the Go layer fell through to the default branch and got the dummy driver. Chat, list models, and check connection all returned dummy responses instead of reaching the API. OpenAI is the most commonly requested provider and the JSON config already ships with the repo, so this gap is high impact even though the JSON has been there for some time. ### What this PR includes - New file internal/entity/models/openai.go with an OpenAIModel that implements the ModelDriver interface. - factory.go: route the "openai" provider name to NewOpenAIModel. - conf/models/openai.json: add "models": "models" under url_suffix so ListModels can hit /v1/models with no hardcoded fallback. ### How the driver works - OpenAI exposes the canonical OpenAI-compatible API at https://api.openai.com/v1. - ChatWithMessages and ChatStreamlyWithSender post to /chat/completions in the same shape the moonshot, vllm, and xai drivers use. - ListModels and CheckConnection call /models to list available ids and confirm the API key works. - reasoning_content is passed through for the o-series and other reasoning models, in both the non-stream and stream paths. - Encode (embeddings) is left as "not implemented" for now, the same way the other recent provider drivers do it. Rerank and Balance are not part of OpenAI's public API surface in this layer and return a clear "not implemented" or "no such method" error. ### Type of change - [x] New Feature (non-breaking change which adds functionality) ### How was this tested? - go build ./internal/entity/models/... in a clean go 1.25 image (the go.mod minimum) returns exit 0 with no errors. - Method set of OpenAIModel matches the ModelDriver interface: NewInstance, Name, ChatWithMessages, ChatStreamlyWithSender, Encode, Rerank, ListModels, Balance, CheckConnection. - Pattern parity with the merged moonshot (infiniflow#14433), volcengine (infiniflow#14460), minimax (infiniflow#14478), vllm (infiniflow#14532), xai (infiniflow#14550), and lm-studio (infiniflow#14586) PRs. Closes infiniflow#14604
What problem does this PR solve?
implement MiniMax provider
Type of change