Skip to content

Fix go cli models command and api - #14166

Merged
JinHai-CN merged 2 commits into
infiniflow:mainfrom
JinHai-CN:fix387
Apr 17, 2026
Merged

JinHai-CN merged 2 commits into
infiniflow:mainfrom
JinHai-CN:fix387

Conversation

@JinHai-CN

Copy link
Copy Markdown
Member

What problem does this PR solve?

RAGFlow(user)> list providers;
+--------------------------------------+----------+-------------------------------------------+--------------+
| base_url                             | name     | tags                                      | total_models |
+--------------------------------------+----------+-------------------------------------------+--------------+
| https://open.bigmodel.cn/api/paas/v4 | ZHIPU-AI | LLM,TEXT EMBEDDING,SPEECH2TEXT,MODERATION | 21           |
| https://api.x.ai/v1                  | xAI      | LLM                                       | 6            |
+--------------------------------------+----------+-------------------------------------------+--------------+
RAGFlow(user)> show provider 'zhipu-ai';
+--------------------------------------+----------+-------------------------------------------+--------------+
| base_url                             | name     | tags                                      | total_models |
+--------------------------------------+----------+-------------------------------------------+--------------+
| https://open.bigmodel.cn/api/paas/v4 | ZHIPU-AI | LLM,TEXT EMBEDDING,SPEECH2TEXT,MODERATION | 21           |
+--------------------------------------+----------+-------------------------------------------+--------------+
RAGFlow(user)> delete provider 'zhipu-ai';
SUCCESS
RAGFlow(user)> add provider 'zhipu-ai';
SUCCESS
RAGFlow(user)> create provider 'zhipu-ai' instance 'ccc' 'ccxxccxx';
SUCCESS
RAGFlow(user)> list instances from 'zhipu-ai';
+---------------------------------------------------+----------------------------------+--------------+----------------------------------+--------+
| apiKey                                            | id                               | instanceName | providerID                       | status |
+---------------------------------------------------+----------------------------------+--------------+----------------------------------+--------+
| ccxxccxx | 640dd7ee398711f1bdd838a74640adcc | ccc          | d1d59de5398411f1bdd838a74640adcc | active |
+---------------------------------------------------+----------------------------------+--------------+----------------------------------+--------+
RAGFlow(user)> list models from 'zhipu-ai';
+----------+------------+---------------+---------------+
| features | max_tokens | model_types   | name          |
+----------+------------+---------------+---------------+
| map[]    | 128000     | [chat]        | glm-4.7       |
| map[]    | 128000     | [chat]        | glm-4.5       |
| map[]    | 128000     | [chat]        | glm-4.5-x     |
| map[]    | 128000     | [chat]        | glm-4.5-air   |
| map[]    | 128000     | [chat]        | glm-4.5-airx  |
| map[]    | 128000     | [chat]        | glm-4.5-flash |
| map[]    | 64000      | [image2text]  | glm-4.5v      |
| map[]    | 128000     | [chat]        | glm-4-plus    |
| map[]    | 128000     | [chat]        | glm-4-0520    |
| map[]    | 128000     | [chat]        | glm-4         |
| map[]    | 8000       | [chat]        | glm-4-airx    |
| map[]    | 128000     | [chat]        | glm-4-air     |
| map[]    | 128000     | [chat]        | glm-4-flash   |
| map[]    | 128000     | [chat]        | glm-4-flashx  |
| map[]    | 1000000    | [chat]        | glm-4-long    |
| map[]    | 128000     | [chat]        | glm-3-turbo   |
| map[]    | 2000       | [image2text]  | glm-4v        |
| map[]    | 8192       | [chat]        | glm-4-9b      |
| map[]    | 512        | [embedding]   | embedding-2   |
| map[]    | 512        | [embedding]   | embedding-3   |
| map[]    | 4096       | [speech2text] | glm-asr       |
+----------+------------+---------------+---------------+
RAGFlow(user)> disable model 'glm-4.5-flash' from 'zhipu-ai' 'ccc';
SUCCESS
RAGFlow(user)> drop instance 'ccc' from 'zhipu-ai';
SUCCESS
RAGFlow(user)> list instances from 'zhipu-ai';
No data to print

@coderabbitai

coderabbitai Bot commented Apr 16, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This pull request refactors provider and model management APIs to align with REST semantics. Provider creation switches from POST to PUT, instance deletion changes from single-resource deletion to batch deletion via request payload, model state updates switch from PUT to PATCH, and supporting handler/service layers are updated accordingly.

Changes

Cohort / File(s) Summary
HTTP Method & Route Updates
internal/cli/user_command.go, internal/router/router.go
Provider creation endpoint changed from POST /providers to PUT /providers. Instance deletion changed from DELETE /providers/{provider}/instances/{instance} to DELETE /providers/{provider}/instances with batch payload. Model updates changed from PUT to PATCH on /providers/{provider}/instances/{instance}/models/{model}.
Request/Response DTO Changes
internal/handler/providers.go
Added DropProviderInstanceRequest struct with Instances []string field. Handler now accepts JSON request body instead of path parameter for instance deletion, supporting batch operations.
Service Layer Logic
internal/service/model_service.go
Replaced single-instance DropProviderInstance method with batch DropProviderInstances that iterates over provided instance list. Updated ModelType derivation to use provider manager lookup. Adjusted parameter types from *model.ChatConfig to *modelModule.ChatConfig.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 HTTP verbs dancing in a line,
PUT and PATCH now align,
Batch deletions, sleek and tight,
REST semantics shining bright!

🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description includes a transcript demonstrating CLI/API functionality but does not address the required template sections about problem statement and type of change. Fill in the template sections: 'What problem does this PR solve?' (explain the API changes) and 'Type of change' (select Bug Fix, New Feature, Refactoring, or Other).
Title check ❓ Inconclusive The title is vague and generic, using non-descriptive terms that don't clearly convey the specific changes made to the codebase. Provide a more specific title that describes the primary change, such as 'Update provider and model API endpoints to use PUT/PATCH/DELETE with collection-based operations'.
✅ Passed checks (1 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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

@JinHai-CN JinHai-CN added the ci Continue Integration label Apr 16, 2026
@JinHai-CN
JinHai-CN marked this pull request as ready for review April 16, 2026 12:36
@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label Apr 16, 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: 3

🤖 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/handler/providers.go`:
- Around line 418-429: The handler currently discards the error code returned by
h.modelProviderService.DropProviderInstances (called with providerName, userID,
req.Instances) and always returns common.CodeServerError; change the call to
capture both returned values (e.g., errCode, err :=
h.modelProviderService.DropProviderInstances(...)), then when returning the JSON
error response use the errCode instead of hardcoding common.CodeServerError so
meanings like common.CodeNotFound propagate correctly alongside err.Error().

In `@internal/service/model_service.go`:
- Around line 473-484: The code assigns modelSchema.ModelTypes[0] to
TenantModel.ModelType without checking for an empty slice, which can panic;
update the block around modelSchema (from GetModelByName) to validate
len(modelSchema.ModelTypes) > 0 before using index 0 and handle the empty case
(e.g., return an appropriate error code/message or set a sensible default) so
entity.TenantModel.ModelType is only set from a non-empty ModelTypes slice.
- Around line 374-383: The current loop calling
m.modelInstanceDAO.DeleteByProviderIDAndInstanceName for each entry in instances
can leave partial deletions if one iteration fails; to fix, either (A) validate
all instances exist before deleting by querying the DAO (e.g., a bulk lookup or
per-instance existence check using provider.ID and the instance names) and
return CodeNotFound if any are missing, or (B) perform the deletions inside a
database transaction (begin transaction, call the same
DeleteByProviderIDAndInstanceName for each instance, commit on success or
rollback on any error) so the operation is atomic; locate the code around the
instances loop and m.modelInstanceDAO.DeleteByProviderIDAndInstanceName to
implement one of these approaches.
🪄 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: 63954d12-223d-4f0a-b737-a8bd164b4e58

📥 Commits

Reviewing files that changed from the base of the PR and between 8a874c7 and 30e3849.

📒 Files selected for processing (4)
  • internal/cli/user_command.go
  • internal/handler/providers.go
  • internal/router/router.go
  • internal/service/model_service.go

Comment on lines +418 to +429
var req DropProviderInstanceRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusOK, gin.H{
"code": common.CodeBadRequest,
"message": err.Error(),
})
return
}

userID := c.GetString("user_id")

_, err := h.modelProviderService.DropProviderInstance(providerName, instanceName, userID)
_, err := h.modelProviderService.DropProviderInstances(providerName, userID, req.Instances)

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 code from service is not being propagated correctly.

The service method DropProviderInstances returns (common.ErrorCode, error), but on line 429 the returned error code is discarded (_). On line 432, CodeServerError is hardcoded, but the service might return CodeNotFound when an instance doesn't exist. This loses meaningful error information.

🔧 Proposed fix to propagate the error code
 	userID := c.GetString("user_id")

-	_, err := h.modelProviderService.DropProviderInstances(providerName, userID, req.Instances)
+	errorCode, err := h.modelProviderService.DropProviderInstances(providerName, userID, req.Instances)
 	if err != nil {
 		c.JSON(http.StatusOK, gin.H{
-			"code":    common.CodeServerError,
+			"code":    errorCode,
 			"message": err.Error(),
 		})
 		return
 	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/handler/providers.go` around lines 418 - 429, The handler currently
discards the error code returned by h.modelProviderService.DropProviderInstances
(called with providerName, userID, req.Instances) and always returns
common.CodeServerError; change the call to capture both returned values (e.g.,
errCode, err := h.modelProviderService.DropProviderInstances(...)), then when
returning the JSON error response use the errCode instead of hardcoding
common.CodeServerError so meanings like common.CodeNotFound propagate correctly
alongside err.Error().

Comment on lines +374 to 383
for _, instanceName := range instances {
count, err := m.modelInstanceDAO.DeleteByProviderIDAndInstanceName(provider.ID, instanceName)
if err != nil {
return common.CodeServerError, err
}

if count == 0 {
return common.CodeNotFound, errors.New("provider instance not found")
if count == 0 {
return common.CodeNotFound, errors.New("provider instance not found")
}
}

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

Batch deletion may leave partial state on failure.

The loop deletes instances one by one. If instance N fails (either due to error or count == 0), instances 0 through N-1 have already been deleted. This creates a non-atomic operation that can leave the system in an inconsistent state.

Consider:

  1. Validating all instances exist before deleting any, or
  2. Wrapping the deletions in a transaction, or
  3. Documenting this as best-effort deletion behavior in the API contract.
🤖 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 374 - 383, The current loop
calling m.modelInstanceDAO.DeleteByProviderIDAndInstanceName for each entry in
instances can leave partial deletions if one iteration fails; to fix, either (A)
validate all instances exist before deleting by querying the DAO (e.g., a bulk
lookup or per-instance existence check using provider.ID and the instance names)
and return CodeNotFound if any are missing, or (B) perform the deletions inside
a database transaction (begin transaction, call the same
DeleteByProviderIDAndInstanceName for each instance, commit on success or
rollback on any error) so the operation is atomic; locate the code around the
instances loop and m.modelInstanceDAO.DeleteByProviderIDAndInstanceName to
implement one of these approaches.

Comment on lines +473 to +484

var modelSchema *entity.Model
modelSchema, err = dao.GetModelProviderManager().GetModelByName(providerName, modelName)
if err != nil {
return common.CodeNotFound, errors.New(fmt.Sprintf("provider %s model %s not found", providerName, modelName))
}

// Get model info from provider
model = &entity.TenantModel{
ID: modelID,
ModelName: modelName,
ModelType: model.ModelType,
ModelType: modelSchema.ModelTypes[0],

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

Potential index out of bounds if ModelTypes is empty.

Accessing modelSchema.ModelTypes[0] without checking the slice length will panic if ModelTypes is an empty slice. Although the context snippet confirms ModelTypes is []string, the data could still be empty.

🛡️ Proposed fix to add bounds check
 		var modelSchema *entity.Model
 		modelSchema, err = dao.GetModelProviderManager().GetModelByName(providerName, modelName)
 		if err != nil {
 			return common.CodeNotFound, errors.New(fmt.Sprintf("provider %s model %s not found", providerName, modelName))
 		}

+		if len(modelSchema.ModelTypes) == 0 {
+			return common.CodeServerError, errors.New(fmt.Sprintf("model %s has no model types defined", modelName))
+		}
+
 		// Get model info from provider
 		model = &entity.TenantModel{
 			ID:         modelID,
 			ModelName:  modelName,
 			ModelType:  modelSchema.ModelTypes[0],
📝 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 modelSchema *entity.Model
modelSchema, err = dao.GetModelProviderManager().GetModelByName(providerName, modelName)
if err != nil {
return common.CodeNotFound, errors.New(fmt.Sprintf("provider %s model %s not found", providerName, modelName))
}
// Get model info from provider
model = &entity.TenantModel{
ID: modelID,
ModelName: modelName,
ModelType: model.ModelType,
ModelType: modelSchema.ModelTypes[0],
var modelSchema *entity.Model
modelSchema, err = dao.GetModelProviderManager().GetModelByName(providerName, modelName)
if err != nil {
return common.CodeNotFound, errors.New(fmt.Sprintf("provider %s model %s not found", providerName, modelName))
}
if len(modelSchema.ModelTypes) == 0 {
return common.CodeServerError, errors.New(fmt.Sprintf("model %s has no model types defined", modelName))
}
// Get model info from provider
model = &entity.TenantModel{
ID: modelID,
ModelName: modelName,
ModelType: modelSchema.ModelTypes[0],
🤖 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 473 - 484, The code assigns
modelSchema.ModelTypes[0] to TenantModel.ModelType without checking for an empty
slice, which can panic; update the block around modelSchema (from
GetModelByName) to validate len(modelSchema.ModelTypes) > 0 before using index 0
and handle the empty case (e.g., return an appropriate error code/message or set
a sensible default) so entity.TenantModel.ModelType is only set from a non-empty
ModelTypes slice.

@codecov

codecov Bot commented Apr 16, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 96.66%. Comparing base (655dd2f) to head (30e3849).
⚠️ Report is 6 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14166   +/-   ##
=======================================
  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.

@JinHai-CN
JinHai-CN merged commit e03212f into infiniflow:main Apr 17, 2026
2 checks passed
@coderabbitai coderabbitai Bot mentioned this pull request Apr 27, 2026
1 task done
JasleenKaurSethi pushed a commit to stackhpc/ragflow that referenced this pull request Apr 28, 2026
### What problem does this PR solve?

```
RAGFlow(user)> list providers;
+--------------------------------------+----------+-------------------------------------------+--------------+
| base_url                             | name     | tags                                      | total_models |
+--------------------------------------+----------+-------------------------------------------+--------------+
| https://open.bigmodel.cn/api/paas/v4 | ZHIPU-AI | LLM,TEXT EMBEDDING,SPEECH2TEXT,MODERATION | 21           |
| https://api.x.ai/v1                  | xAI      | LLM                                       | 6            |
+--------------------------------------+----------+-------------------------------------------+--------------+
RAGFlow(user)> show provider 'zhipu-ai';
+--------------------------------------+----------+-------------------------------------------+--------------+
| base_url                             | name     | tags                                      | total_models |
+--------------------------------------+----------+-------------------------------------------+--------------+
| https://open.bigmodel.cn/api/paas/v4 | ZHIPU-AI | LLM,TEXT EMBEDDING,SPEECH2TEXT,MODERATION | 21           |
+--------------------------------------+----------+-------------------------------------------+--------------+
RAGFlow(user)> delete provider 'zhipu-ai';
SUCCESS
RAGFlow(user)> add provider 'zhipu-ai';
SUCCESS
RAGFlow(user)> create provider 'zhipu-ai' instance 'ccc' 'ccxxccxx';
SUCCESS
RAGFlow(user)> list instances from 'zhipu-ai';
+---------------------------------------------------+----------------------------------+--------------+----------------------------------+--------+
| apiKey                                            | id                               | instanceName | providerID                       | status |
+---------------------------------------------------+----------------------------------+--------------+----------------------------------+--------+
| ccxxccxx | 640dd7ee398711f1bdd838a74640adcc | ccc          | d1d59de5398411f1bdd838a74640adcc | active |
+---------------------------------------------------+----------------------------------+--------------+----------------------------------+--------+
RAGFlow(user)> list models from 'zhipu-ai';
+----------+------------+---------------+---------------+
| features | max_tokens | model_types   | name          |
+----------+------------+---------------+---------------+
| map[]    | 128000     | [chat]        | glm-4.7       |
| map[]    | 128000     | [chat]        | glm-4.5       |
| map[]    | 128000     | [chat]        | glm-4.5-x     |
| map[]    | 128000     | [chat]        | glm-4.5-air   |
| map[]    | 128000     | [chat]        | glm-4.5-airx  |
| map[]    | 128000     | [chat]        | glm-4.5-flash |
| map[]    | 64000      | [image2text]  | glm-4.5v      |
| map[]    | 128000     | [chat]        | glm-4-plus    |
| map[]    | 128000     | [chat]        | glm-4-0520    |
| map[]    | 128000     | [chat]        | glm-4         |
| map[]    | 8000       | [chat]        | glm-4-airx    |
| map[]    | 128000     | [chat]        | glm-4-air     |
| map[]    | 128000     | [chat]        | glm-4-flash   |
| map[]    | 128000     | [chat]        | glm-4-flashx  |
| map[]    | 1000000    | [chat]        | glm-4-long    |
| map[]    | 128000     | [chat]        | glm-3-turbo   |
| map[]    | 2000       | [image2text]  | glm-4v        |
| map[]    | 8192       | [chat]        | glm-4-9b      |
| map[]    | 512        | [embedding]   | embedding-2   |
| map[]    | 512        | [embedding]   | embedding-3   |
| map[]    | 4096       | [speech2text] | glm-asr       |
+----------+------------+---------------+---------------+
RAGFlow(user)> disable model 'glm-4.5-flash' from 'zhipu-ai' 'ccc';
SUCCESS
RAGFlow(user)> drop instance 'ccc' from 'zhipu-ai';
SUCCESS
RAGFlow(user)> list instances from 'zhipu-ai';
No data to print
```

Signed-off-by: Jin Hai <[email protected]>
@coderabbitai coderabbitai Bot mentioned this pull request Apr 30, 2026
2 of 6 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant