Skip to content

Go: add new provider minimax - #14296

Merged
JinHai-CN merged 3 commits into
infiniflow:mainfrom
JinHai-CN:fix498
Apr 23, 2026
Merged

JinHai-CN merged 3 commits into
infiniflow:mainfrom
JinHai-CN:fix498

Conversation

@JinHai-CN

Copy link
Copy Markdown
Member

What problem does this PR solve?

  1. Add new provider minimax
  2. Add new command: CHECK INSTANCE 'instance_name' FROM 'provider_name';
RAGFlow(user)> check instance 'test' from 'minimax';
SUCCESS

Type of change

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

@coderabbitai

coderabbitai Bot commented Apr 22, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This PR adds a provider connection checking feature across multiple layers: new Minimax provider configuration, CLI support for a CHECK command to validate provider instance connectivity, model driver interface extensions, HTTP handler/router endpoint, and service layer orchestration for checking connections via the appropriate driver.

Changes

Cohort / File(s) Summary
Model Configurations
conf/models/deepseek.json, conf/models/moonshot.json, conf/models/openai.json, conf/models/xai.json
Removed empty features: {} fields from per-model entries while preserving name, max_tokens, and model_types.
Minimax Provider Config
conf/models/minimax.json
New configuration file defining MiniMax provider with base URLs, endpoint suffixes (chat, tts, files), eight chat models, and thinking capability support.
Zhipu AI Provider Config
conf/models/zhipu-ai.json
Added new models (glm-5\*, glm-4.7-flashx), increased max\_tokens limits, added files endpoint suffix, removed per-model features fields, removed glm-3-turbo, and updated thinking/clear\_thinking supported models lists.
CLI Token & Keyword Recognition
internal/cli/types.go, internal/cli/lexer.go
Added TokenCheck constant and case-insensitive CHECK keyword recognition in lexer.
CLI Parser for CHECK Command
internal/cli/parser.go, internal/cli/user_parser.go
Extended command dispatch to recognize TokenCheck and added parseCheckCommand() to parse CHECK INSTANCE <name> FROM <provider> syntax.
CLI Command Execution
internal/cli/client.go, internal/cli/user_command.go
Added command dispatch for check_provider_connection type and new CheckProviderConnection() method that validates tokens, constructs GET request to /providers/{providerName}/instances/{instanceName}/connection, and returns unmarshaled response.
Model Driver Interface & Types
internal/entity/models/types.go
Extended ModelDriver interface with CheckConnection(apiConfig *APIConfig) error method and added Files field to URLSuffix.
Model Driver Implementations
internal/entity/models/deepseek.go, internal/entity/models/dummy.go, internal/entity/models/moonshot.go, internal/entity/models/zhipu-ai.go
Added CheckConnection() implementations; DeepSeek and Moonshot delegate to ListModels(), ZhipuAI performs direct HTTP validation with region-aware URL construction, Dummy returns error.
Minimax Model Driver
internal/entity/models/minimax.go
New driver implementing ModelDriver interface with region-aware base URLs, timeouts, connection pooling, and CheckConnection() method performing authenticated GET request to files endpoint.
Model Factory
internal/entity/models/factory.go
Added minimax provider case in CreateModelDriver() to instantiate MinimaxModel.
HTTP Handler
internal/handler/providers.go
Added CheckProviderConnection() handler extracting route params, validating inputs, calling service method, and returning success/error responses.
Router Endpoint
internal/router/router.go
Registered authenticated route GET /api/v1/providers/:provider_name/instances/:instance_name/connection mapped to handler.
Service Layer
internal/service/model_service.go
Added CheckProviderConnection() service method coordinating tenant resolution, provider/instance lookup, API config construction from instance metadata, and delegating to driver's CheckConnection().

Sequence Diagram

sequenceDiagram
    participant User
    participant CLI as CLI Client
    participant Parser
    participant Handler as HTTP Handler
    participant Service as Model Service
    participant DAO as Data Access
    participant Driver as Model Driver
    participant API as External API

    User->>CLI: CHECK INSTANCE myInstance FROM minimax
    CLI->>Parser: Parse command
    Parser->>Parser: Match TokenCheck, extract params
    Parser-->>CLI: Return check_provider_connection command
    CLI->>Handler: GET /providers/minimax/instances/myInstance/connection
    Handler->>Handler: Validate provider_name, instance_name
    Handler->>Service: CheckProviderConnection(minimax, myInstance, userID)
    Service->>DAO: GetByUserIDAndRole(userID, owner)
    DAO-->>Service: Return tenant
    Service->>DAO: Load provider config & instance
    DAO-->>Service: Return provider & instance details
    Service->>Service: Build APIConfig with region & apiKey
    Service->>Driver: CheckConnection(apiConfig)
    Driver->>API: GET /files (with Authorization header)
    API-->>Driver: 200 OK or error status
    Driver-->>Service: Return nil or error
    Service-->>Handler: Return (CodeSuccess, nil) or error
    Handler-->>CLI: HTTP 200 {code: 0, message: success}
    CLI-->>User: Connection verified
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Possibly related PRs

  • Add extra field to model instance #14203: Modifies model-driver connection surface with region-aware URL handling, files endpoint suffix, and CheckConnection logic that directly relate to this PR's interface extensions and driver implementations.
  • Go: add stream / think chat #14242: Implements large model-driver refactor affecting the same ModelDriver interface, type definitions, and new provider integrations (DeepSeek, Moonshot) that this PR extends with connection checking capabilities.

Suggested labels

size:XL

Poem

🐰 A minimax mouse checked the connection,
Through deepseek tunnels with zhipu's perfection,
The moonshot path glowed, each provider aligned,
With tokens and handlers in harmony designed!
From CLI to driver, the feature took flight,
A connection check dancing from left to right! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main feature addition: supporting a new 'minimax' provider with comprehensive backend integration.
Description check ✅ Passed The description includes both required sections from the template and clearly articulates two key features being added, though it could be more detailed about technical implementation.
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.

✏️ 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 22, 2026
@JinHai-CN
JinHai-CN marked this pull request as ready for review April 22, 2026 10:20
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. 💞 feature Feature request, pull request that fullfill a new feature. labels Apr 22, 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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
conf/models/zhipu-ai.json (1)

224-250: ⚠️ Potential issue | 🟡 Minor

Update feature-supported model names to match configured models.

glm-4.6v is referenced in both the thinking and clear_thinking features, but the model list contains glm-4.6v-Flash. This mismatch will prevent the vision model from receiving these feature flags.

Suggested fix
-        "glm-4.6v",
+        "glm-4.6v-Flash",

Update both occurrences in the thinking and clear_thinking feature maps.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@conf/models/zhipu-ai.json` around lines 224 - 250, Replace the incorrect
model name "glm-4.6v" with the configured "glm-4.6v-Flash" inside both feature
maps: the "thinking" feature's supported_models array and the "clear_thinking"
feature's supported_models array so the vision model receives the correct
feature flags.
🧹 Nitpick comments (3)
internal/entity/models/moonshot.go (1)

184-190: Nit: simplify CheckConnection.

The if err != nil { return err } wrapper is redundant; a direct return is cleaner.

Proposed simplification
 func (z *MoonshotModel) CheckConnection(apiConfig *APIConfig) error {
-	_, err := z.ListModels(apiConfig)
-	if err != nil {
-		return err
-	}
-	return nil
+	_, err := z.ListModels(apiConfig)
+	return err
 }

Note: same pattern appears in internal/entity/models/deepseek.go; consider applying there as well.

🤖 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 184 - 190, Simplify the
redundant error wrapper in CheckConnection: replace the explicit if-check in
MoonshotModel.CheckConnection by returning the result of z.ListModels(apiConfig)
directly (i.e., return z.ListModels(apiConfig)); apply the same simplification
to the identical pattern in DeepseekModel.CheckConnection in
internal/entity/models/deepseek.go so both functions return the call result
directly instead of checking err and returning nil.
internal/entity/models/deepseek.go (1)

139-145: Simplify CheckConnection.

The if err != nil { return err }; return nil pair is equivalent to returning err directly. Same pattern appears in moonshot.go:184-190; feel free to leave both consistent if you prefer the longer form.

♻️ Optional simplification
 func (z *DeepSeekModel) CheckConnection(apiConfig *APIConfig) error {
 	_, err := z.ListModels(apiConfig)
-	if err != nil {
-		return err
-	}
-	return nil
+	return err
 }
🤖 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 139 - 145, The
CheckConnection method in DeepSeekModel currently uses an unnecessary if/return
pattern; change DeepSeekModel.CheckConnection to directly return the error from
z.ListModels(apiConfig) (i.e., return err) instead of the if err != nil { return
err }; return nil block; optionally apply the same simplification to the similar
method referenced in moonshot.go (lines ~184-190) to keep style consistent.
internal/service/model_service.go (1)

479-529: Heavy duplication with ShowInstanceBalance / ListSupportedModels — extract a helper.

Lines 481–522 are essentially the same sequence already present in ShowInstanceBalance (lines 428–469) and ListSupportedModels (lines 234–275): resolve tenant → resolve provider → resolve instance → find driver → unmarshal Extra → build APIConfig. Consider extracting something like:

func (m *ModelProviderService) resolveDriverContext(userID, providerName, instanceName string) (
    *dao.ProviderInfo, *modelModule.APIConfig, common.ErrorCode, error) { ... }

The only driver-specific call (ModelDriver.CheckConnection(apiConfig)) would remain in this method. This removes ~40 lines here and makes future driver calls (e.g., a follow-up “chat test” variant) trivial, and it centralizes the error-code mapping (tenant-missing vs. provider-missing vs. unmarshal failure) so behavior stays uniform across endpoints.

Not a blocker for this PR, but worth tackling while these three methods are fresh.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/service/model_service.go` around lines 479 - 529, Extract the
duplicated tenant→provider→instance→driver resolution logic used in
CheckProviderConnection, ShowInstanceBalance, and ListSupportedModels into a new
helper on ModelProviderService named resolveDriverContext(userID, providerName,
instanceName string) returning (*dao.ProviderInfo, *modelModule.APIConfig,
common.ErrorCode, error); have the helper perform
userTenantDAO.GetByUserIDAndRole, modelProviderDAO.GetByTenantIDAndProviderName,
modelInstanceDAO.GetByProviderIDAndInstanceName,
dao.GetModelProviderManager().FindProvider, json.Unmarshal of instance.Extra and
build the APIConfig (setting Region and ApiKey) and map specific failure cases
to the same common.ErrorCode + error values currently used; then replace the
duplicated blocks in CheckProviderConnection (and the similar blocks in
ShowInstanceBalance and ListSupportedModels) by calling resolveDriverContext and
keep only the driver-specific call (e.g.,
providerInfo.ModelDriver.CheckConnection(apiConfig)) in each original method.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@conf/models/minimax.json`:
- Around line 70-77: The features.thinking.supported_models entry in the MiniMax
config is wrong (it lists "deepseek-chat" from another provider); update the
"features.thinking.supported_models" array to include the actual MiniMax model
identifiers from this provider's models list (or remove the entire "thinking"
feature block if no MiniMax models support it) and ensure the default_value for
features.thinking matches the real supported-model semantics so consumers
filtering by supported_models will behave correctly.

In `@internal/entity/models/deepseek.go`:
- Around line 62-64: The ChatStreamlyWithSender implementation for DeepSeekModel
currently returns nil and falsely signals success; update
DeepSeekModel.ChatStreamlyWithSender to return a proper "not implemented" error
consistent with other stubs (e.g., MinimaxModel.ChatStreamlyWithSender) such as:
return fmt.Errorf("%s, no such method", z.Name()); ensure you import fmt if not
present and keep the function signature unchanged so callers detect the error
instead of treating it as success.

In `@internal/entity/models/minimax.go`:
- Around line 26-34: Update the copied doc comments in this file to refer to the
Minimax driver instead of "Zhipu AI": change the comment above the MinimaxModel
type and the NewMinimaxModel constructor so they describe the Minimax
model/driver (e.g., "MinimaxModel implements ModelDriver for Minimax" and
"NewMinimaxModel creates a new Minimax model instance"), leaving the symbol
names MinimaxModel and NewMinimaxModel unchanged.
- Around line 64-67: The EncodeToEmbedding stub returns a non-conforming error
string ("not implemented"); change it to match the other stubs by returning
fmt.Errorf("%s, no such method", z.Name()) so error messages are uniform—update
the EncodeToEmbedding method in minimax.go to use z.Name() in the fmt.Errorf
exactly like Chat, ChatStreamlyWithSender, ListModels, and Balance.
- Around line 77-109: The CheckConnection method in MinimaxModel is building the
files URL without the required purpose query parameter, causing the API to
return 4xx; update the URL construction in CheckConnection to include the
required query string (e.g., append "?purpose=retrieval") or switch the
health-check to a supported endpoint like /v1/text/chatcompletion_v2 or
/v1/models, and ensure the Authorization header and response handling remain
unchanged; also correct the copy-paste comment that mentions "Zhipu AI" to
instead reference "MiniMax" near the MinimaxModel/type declaration.

In `@internal/entity/models/zhipu-ai.go`:
- Around line 429-461: The CheckConnection method is calling the Files endpoint
(z.URLSuffix.Files) which requires a purpose query and is unsuitable for auth
probing; update CheckConnection to call the chat completions endpoint instead by
using z.URLSuffix.Chat (or "chat/completions") when building the URL from
z.BaseURL[region], so the request to z.httpClient.Do(req) will return proper
401/200 auth responses; alternatively, if you must use Files, append the
required query parameter (e.g., ?purpose=batch) to the URL before creating the
request and keep all existing header/auth handling.

---

Outside diff comments:
In `@conf/models/zhipu-ai.json`:
- Around line 224-250: Replace the incorrect model name "glm-4.6v" with the
configured "glm-4.6v-Flash" inside both feature maps: the "thinking" feature's
supported_models array and the "clear_thinking" feature's supported_models array
so the vision model receives the correct feature flags.

---

Nitpick comments:
In `@internal/entity/models/deepseek.go`:
- Around line 139-145: The CheckConnection method in DeepSeekModel currently
uses an unnecessary if/return pattern; change DeepSeekModel.CheckConnection to
directly return the error from z.ListModels(apiConfig) (i.e., return err)
instead of the if err != nil { return err }; return nil block; optionally apply
the same simplification to the similar method referenced in moonshot.go (lines
~184-190) to keep style consistent.

In `@internal/entity/models/moonshot.go`:
- Around line 184-190: Simplify the redundant error wrapper in CheckConnection:
replace the explicit if-check in MoonshotModel.CheckConnection by returning the
result of z.ListModels(apiConfig) directly (i.e., return
z.ListModels(apiConfig)); apply the same simplification to the identical pattern
in DeepseekModel.CheckConnection in internal/entity/models/deepseek.go so both
functions return the call result directly instead of checking err and returning
nil.

In `@internal/service/model_service.go`:
- Around line 479-529: Extract the duplicated tenant→provider→instance→driver
resolution logic used in CheckProviderConnection, ShowInstanceBalance, and
ListSupportedModels into a new helper on ModelProviderService named
resolveDriverContext(userID, providerName, instanceName string) returning
(*dao.ProviderInfo, *modelModule.APIConfig, common.ErrorCode, error); have the
helper perform userTenantDAO.GetByUserIDAndRole,
modelProviderDAO.GetByTenantIDAndProviderName,
modelInstanceDAO.GetByProviderIDAndInstanceName,
dao.GetModelProviderManager().FindProvider, json.Unmarshal of instance.Extra and
build the APIConfig (setting Region and ApiKey) and map specific failure cases
to the same common.ErrorCode + error values currently used; then replace the
duplicated blocks in CheckProviderConnection (and the similar blocks in
ShowInstanceBalance and ListSupportedModels) by calling resolveDriverContext and
keep only the driver-specific call (e.g.,
providerInfo.ModelDriver.CheckConnection(apiConfig)) in each original method.
🪄 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: 8e252f50-ceeb-423c-bf32-01d4ebdb1baa

📥 Commits

Reviewing files that changed from the base of the PR and between 38e45a1 and 6556c65.

📒 Files selected for processing (22)
  • conf/models/deepseek.json
  • conf/models/minimax.json
  • conf/models/moonshot.json
  • conf/models/openai.json
  • conf/models/xai.json
  • conf/models/zhipu-ai.json
  • internal/cli/client.go
  • internal/cli/lexer.go
  • internal/cli/parser.go
  • internal/cli/types.go
  • internal/cli/user_command.go
  • internal/cli/user_parser.go
  • internal/entity/models/deepseek.go
  • internal/entity/models/dummy.go
  • internal/entity/models/factory.go
  • internal/entity/models/minimax.go
  • internal/entity/models/moonshot.go
  • internal/entity/models/types.go
  • internal/entity/models/zhipu-ai.go
  • internal/handler/providers.go
  • internal/router/router.go
  • internal/service/model_service.go

Comment thread conf/models/minimax.json
Comment on lines +70 to +77
"features": {
"thinking": {
"default_value": true,
"supported_models": [
"deepseek-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 | 🟠 Major

Likely copy-paste bug: supported_models lists deepseek-chat in MiniMax config.

The features.thinking.supported_models array contains "deepseek-chat", which is not a model defined in this provider's models list above. This appears to have been copied from another provider's config (e.g., deepseek/zhipu-ai). With default_value: true and no matching supported MiniMax model, the thinking feature flag semantics here are confusing at best and incorrect at worst — consumers filtering by supported_models will never match any MiniMax model, while those trusting default_value will enable thinking universally.

Please populate supported_models with the actual MiniMax models that support thinking (or remove the feature entry if none do).

   "features": {
     "thinking": {
-      "default_value": true,
-      "supported_models": [
-        "deepseek-chat"
-      ]
+      "default_value": true,
+      "supported_models": [
+        // TODO: list MiniMax models that support thinking
+      ]
     }
   }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@conf/models/minimax.json` around lines 70 - 77, The
features.thinking.supported_models entry in the MiniMax config is wrong (it
lists "deepseek-chat" from another provider); update the
"features.thinking.supported_models" array to include the actual MiniMax model
identifiers from this provider's models list (or remove the entire "thinking"
feature block if no MiniMax models support it) and ensure the default_value for
features.thinking matches the real supported-model semantics so consumers
filtering by supported_models will behave correctly.

Comment on lines 62 to 64
func (z *DeepSeekModel) ChatStreamlyWithSender(modelName, message *string, apiConfig *APIConfig, chatModelConfig *ChatConfig, sender func(*string, *string) error) error {
return fmt.Errorf("not implemented")
return 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

ChatStreamlyWithSender silently returns nil — hides “not implemented” and breaks callers.

Before this change, the method returned an error; now any call through DeepSeekModel.ChatStreamlyWithSender succeeds without emitting any data. In internal/service/model_service.go (ChatToModelStreamWithSender, lines 794–797), err == nil is treated as success (return common.CodeSuccess), so the HTTP handler in internal/handler/providers.go will respond “success” for streaming chats against DeepSeek while the SSE body contains nothing — a silent user-visible regression.

Other stubs in this PR (e.g. MinimaxModel.ChatStreamlyWithSender in internal/entity/models/minimax.go:60-62) still return fmt.Errorf("%s, no such method", z.Name()). Please align DeepSeek with that pattern.

🐛 Proposed fix
 func (z *DeepSeekModel) ChatStreamlyWithSender(modelName, message *string, apiConfig *APIConfig, chatModelConfig *ChatConfig, sender func(*string, *string) error) error {
-	return nil
+	return fmt.Errorf("%s, no such method", z.Name())
 }
📝 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) ChatStreamlyWithSender(modelName, message *string, apiConfig *APIConfig, chatModelConfig *ChatConfig, sender func(*string, *string) error) error {
return fmt.Errorf("not implemented")
return nil
}
func (z *DeepSeekModel) ChatStreamlyWithSender(modelName, message *string, apiConfig *APIConfig, chatModelConfig *ChatConfig, sender func(*string, *string) error) error {
return fmt.Errorf("%s, no such method", z.Name())
}
🤖 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 62 - 64, The
ChatStreamlyWithSender implementation for DeepSeekModel currently returns nil
and falsely signals success; update DeepSeekModel.ChatStreamlyWithSender to
return a proper "not implemented" error consistent with other stubs (e.g.,
MinimaxModel.ChatStreamlyWithSender) such as: return fmt.Errorf("%s, no such
method", z.Name()); ensure you import fmt if not present and keep the function
signature unchanged so callers detect the error instead of treating it as
success.

Comment on lines +26 to +34
// MinimaxModel implements ModelDriver for Zhipu AI
type MinimaxModel struct {
BaseURL map[string]string
URLSuffix URLSuffix
httpClient *http.Client // Reusable HTTP client with connection pool
}

// NewMinimaxModel creates a new Zhipu AI model instance
func NewMinimaxModel(baseURL map[string]string, urlSuffix URLSuffix) *MinimaxModel {

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 comments still reference "Zhipu AI".

These doc comments were copied from zhipu-ai.go and weren't updated for the new driver.

📝 Proposed fix
-// MinimaxModel implements ModelDriver for Zhipu AI
+// MinimaxModel implements ModelDriver for MiniMax
 type MinimaxModel struct {
 	BaseURL    map[string]string
 	URLSuffix  URLSuffix
 	httpClient *http.Client // Reusable HTTP client with connection pool
 }

-// NewMinimaxModel creates a new Zhipu AI model instance
+// NewMinimaxModel creates a new MiniMax model instance
 func NewMinimaxModel(baseURL map[string]string, urlSuffix URLSuffix) *MinimaxModel {
📝 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
// MinimaxModel implements ModelDriver for Zhipu AI
type MinimaxModel struct {
BaseURL map[string]string
URLSuffix URLSuffix
httpClient *http.Client // Reusable HTTP client with connection pool
}
// NewMinimaxModel creates a new Zhipu AI model instance
func NewMinimaxModel(baseURL map[string]string, urlSuffix URLSuffix) *MinimaxModel {
// MinimaxModel implements ModelDriver for MiniMax
type MinimaxModel struct {
BaseURL map[string]string
URLSuffix URLSuffix
httpClient *http.Client // Reusable HTTP client with connection pool
}
// NewMinimaxModel creates a new MiniMax model instance
func NewMinimaxModel(baseURL map[string]string, urlSuffix URLSuffix) *MinimaxModel {
🤖 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 26 - 34, Update the copied
doc comments in this file to refer to the Minimax driver instead of "Zhipu AI":
change the comment above the MinimaxModel type and the NewMinimaxModel
constructor so they describe the Minimax model/driver (e.g., "MinimaxModel
implements ModelDriver for Minimax" and "NewMinimaxModel creates a new Minimax
model instance"), leaving the symbol names MinimaxModel and NewMinimaxModel
unchanged.

Comment on lines +64 to +67
// EncodeToEmbedding encodes a list of texts into embeddings
func (z *MinimaxModel) 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 | 🟡 Minor

Error string is inconsistent with the rest of this file.

Every other stubbed method (Chat, ChatStreamlyWithSender, ListModels, Balance) uses fmt.Errorf("%s, no such method", z.Name()). EncodeToEmbedding returns "not implemented" — align it so upstream error-message parsing / user-facing messages are uniform across the driver.

📝 Proposed fix
 func (z *MinimaxModel) EncodeToEmbedding(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([][]float64, error) {
-	return nil, fmt.Errorf("not implemented")
+	return nil, fmt.Errorf("%s, no such method", z.Name())
 }
📝 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
// EncodeToEmbedding encodes a list of texts into embeddings
func (z *MinimaxModel) EncodeToEmbedding(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([][]float64, error) {
return nil, fmt.Errorf("not implemented")
}
// EncodeToEmbedding encodes a list of texts into embeddings
func (z *MinimaxModel) EncodeToEmbedding(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([][]float64, error) {
return nil, fmt.Errorf("%s, no such method", z.Name())
}
🤖 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 64 - 67, The
EncodeToEmbedding stub returns a non-conforming error string ("not
implemented"); change it to match the other stubs by returning fmt.Errorf("%s,
no such method", z.Name()) so error messages are uniform—update the
EncodeToEmbedding method in minimax.go to use z.Name() in the fmt.Errorf exactly
like Chat, ChatStreamlyWithSender, ListModels, and Balance.

Comment on lines +77 to +109
func (z *MinimaxModel) CheckConnection(apiConfig *APIConfig) error {
var region = "default"
if apiConfig.Region != nil {
region = *apiConfig.Region
}

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

req, err := http.NewRequest("GET", url, nil)
if err != nil {
return 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 fmt.Errorf("failed to send request: %w", err)
}
defer resp.Body.Close()

body, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read response: %w", err)
}

if resp.StatusCode != http.StatusOK {
return fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
}

return 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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Inspect the MiniMax provider configuration shipped in this PR.
fd -i -a 'minimax' -e json
fd -i -a 'minimax' -e json --exec cat {}

Repository: infiniflow/ragflow

Length of output: 1463


🏁 Script executed:

cat -n internal/entity/models/minimax.go | head -120

Repository: infiniflow/ragflow

Length of output: 4225


CheckConnection will fail — missing required query parameter for MiniMax's files endpoint.

MiniMax's /v1/files/list API requires a purpose query parameter. The code constructs the URL at line 83 but doesn't append any query parameters, so the request will return 4xx even with valid credentials, making this check always fail.

Add the required purpose query parameter to the URL, e.g., url := fmt.Sprintf("%s/%s?purpose=retrieval", z.BaseURL[region], z.URLSuffix.Files). Alternatively, consider using one of the options from the original review: a billable endpoint like /v1/text/chatcompletion_v2, or the /v1/models endpoint if supported.

Also note: Line 26 contains a copy-paste error — the comment says "Zhipu AI" but should reference "MiniMax".

🤖 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 77 - 109, The CheckConnection
method in MinimaxModel is building the files URL without the required purpose
query parameter, causing the API to return 4xx; update the URL construction in
CheckConnection to include the required query string (e.g., append
"?purpose=retrieval") or switch the health-check to a supported endpoint like
/v1/text/chatcompletion_v2 or /v1/models, and ensure the Authorization header
and response handling remain unchanged; also correct the copy-paste comment that
mentions "Zhipu AI" to instead reference "MiniMax" near the MinimaxModel/type
declaration.

Comment on lines +429 to +461
func (z *ZhipuAIModel) CheckConnection(apiConfig *APIConfig) error {
var region = "default"
if apiConfig.Region != nil {
region = *apiConfig.Region
}

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

req, err := http.NewRequest("GET", url, nil)
if err != nil {
return 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 fmt.Errorf("failed to send request: %w", err)
}
defer resp.Body.Close()

body, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read response: %w", err)
}

if resp.StatusCode != http.StatusOK {
return fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
}

return 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
# Verify url_suffix.files is set for zhipu provider config and inspect the endpoint choice.
fd -e json -i -a 'zhipu'
fd -e json -i -a 'zhipu' --exec cat {}

Repository: infiniflow/ragflow

Length of output: 4311


🌐 Web query:

Zhipu AI API files endpoint GET request authentication

💡 Result:

Zhipu AI (智谱AI) Files API endpoints, including GET requests for file list (/paas/v4/files) and file content (/paas/v4/files/{file_id}/content), use standard Bearer token authentication with an API key. To authenticate a GET request: 1. Obtain an API key from the Zhipu AI Open Platform (https://open.bigmodel.cn/): Register/login, go to API Keys management, create a new key. 2. Use the base URL: https://open.bigmodel.cn/api/paas/v4/ 3. Include the Authorization header: Authorization: Bearer YOUR_API_KEY Example for GET /paas/v4/files (file list, requires ?purpose=... query param): curl "https://open.bigmodel.cn/api/paas/v4/files?purpose=batch&limit=20" \ -H "Authorization: Bearer YOUR_API_KEY" Example for GET /paas/v4/files/{file_id}/content (file content download, supports batch files): curl "https://open.bigmodel.cn/api/paas/v4/files/FILE_ID/content" \ -H "Authorization: Bearer YOUR_API_KEY" \ --output downloaded_file.jsonl All File API endpoints under the "文件 API" tag require this bearerAuth scheme, as defined in the official OpenAPI spec. The API is compatible with OpenAI-style SDKs by setting the base_url.

Citations:


🌐 Web query:

Zhipu open.bigmodel.cn /files endpoint purpose

💡 Result:

The /files endpoint on Zhipu AI's open.bigmodel.cn API (base URL: https://open.bigmodel.cn/api/paas/v4/files) is part of the File API for managing files used in features like batch processing, agents, code interpreters, and voice cloning. It supports: - POST /paas/v4/files: Upload files with a specified purpose (e.g., 'batch' for .jsonl up to 100MB, 'code-interpreter' or 'agent' for docs/images up to 20MB). - GET /paas/v4/files: List uploaded files, filtered by purpose, with pagination. Related endpoints: - DELETE /paas/v4/files/{file_id}: Permanently delete a file. - GET /paas/v4/files/{file_id}/content: Retrieve content (binary) of batch files. - GET /paas/v4/files/{file_id}: Likely retrieve file details (standard in such APIs, though not explicitly snippeted). Files are used for batch tasks, agent tools, code sandboxes, etc., with format and size limits per purpose.

Citations:


🌐 Web query:

Zhipu AI models endpoint API documentation

💡 Result:

Zhipu AI (also known as Z.ai) provides API access to their GLM series of large language models through the official open platform at https://open.bigmodel.cn. The primary endpoint for model interactions is the OpenAI-compatible /chat/completions endpoint. Base URL: https://open.bigmodel.cn/api/paas/v4/ Main Endpoint: POST https://open.bigmodel.cn/api/paas/v4/chat/completions Authentication: Bearer token using API key obtained from the platform console (https://open.bigmodel.cn/dev/api or similar). Official Documentation: https://docs.bigmodel.cn/api-reference/ (primary API reference) and https://docs.bigmodel.cn/cn/guide/start/quick-start (quick start). Key Features: - Supports text, vision (images), audio, video, and multimodal inputs. - Streaming and non-streaming responses. - Tool calling, JSON mode, temperature, top_p, max_tokens, etc., similar to OpenAI. - Models support long contexts (up to 200K+ tokens for some). Available Models (as of 2026-04-22, from official docs and listings): - glm-5.1 (flagship, complex reasoning, long context) - glm-5 - glm-4-0520, glm-4-plus, glm-4-flash, glm-4-long, glm-4-air, glm-4-airx - glm-4v, glm-4v-plus (vision) - glm-4.5 series: glm-4.5, glm-4.5-air, glm-4.5-flash, glm-4.5v - glm-4.6, glm-4.6v - glm-4.7, glm-4.7-flash, glm-4.7-flashx - codegeex-4 (coding) - Multimodal: glm-5v-turbo, etc. Example cURL request: curl -X POST https://open.bigmodel.cn/api/paas/v4/chat/completions \ -H "Authorization: Bearer $YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "glm-5.1", "messages": [{"role": "user", "content": "Hello"}] }' SDKs: Official Python (zhipuai or zai-sdk), Java, compatible with OpenAI SDK (base_url above). Note: For coding-specific use, use https://open.bigmodel.cn/api/coding/paas/v4/. Register at platform for API key and model access.

Citations:


Fix CheckConnection to pass required query parameter or use /chat/completions endpoint.

The url_suffix.files is correctly set in the Zhipu config. However, the Zhipu AI /files endpoint requires a ?purpose= query parameter (e.g., ?purpose=batch), which the code does not provide. The API will return a 400 error even with valid credentials, causing the connection check to fail.

Additionally, /files is designed for file management (listing uploaded files), not connection verification. The /chat/completions endpoint is more appropriate for auth probes—it's the standard API entry point and will return 401 on invalid credentials and 200 on valid ones without special parameters.

Recommended fix: Replace z.URLSuffix.Files with z.URLSuffix.Chat (or directly use "chat/completions"), or if the Files endpoint is intentional, add the required ?purpose=batch query parameter to the URL.

🤖 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 429 - 461, The
CheckConnection method is calling the Files endpoint (z.URLSuffix.Files) which
requires a purpose query and is unsuitable for auth probing; update
CheckConnection to call the chat completions endpoint instead by using
z.URLSuffix.Chat (or "chat/completions") when building the URL from
z.BaseURL[region], so the request to z.httpClient.Do(req) will return proper
401/200 auth responses; alternatively, if you must use Files, append the
required query parameter (e.g., ?purpose=batch) to the URL before creating the
request and keep all existing header/auth handling.

@codecov

codecov Bot commented Apr 22, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95.97%. Comparing base (c08cd8e) to head (14c27e1).
⚠️ Report is 4 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #14296      +/-   ##
==========================================
+ Coverage   95.25%   95.97%   +0.71%     
==========================================
  Files          10       10              
  Lines         695      695              
  Branches      111      111              
==========================================
+ Hits          662      667       +5     
+ Misses         15       11       -4     
+ Partials       18       17       -1     

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

@JinHai-CN
JinHai-CN merged commit 2b02988 into infiniflow:main Apr 23, 2026
1 of 2 checks passed
@coderabbitai coderabbitai Bot mentioned this pull request Apr 24, 2026
1 task done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant