Repository navigation
Go: set and list default models - #14191
Conversation
Signed-off-by: Jin Hai <[email protected]>
📝 WalkthroughWalkthroughAdded support for a new AI model ( Changes
Sequence Diagram(s)sequenceDiagram
participant CLI as CLI Client
participant Handler as Handler
participant Service as TenantService
participant ProviderMgr as ModelProviderManager
participant DAOs as Model DAOs
participant DB as Database
rect rgba(100, 150, 200, 0.5)
Note over CLI,DB: Set Tenant Default Model
CLI->>Handler: PATCH /api/v1/models<br/>(modelProvider, modelInstance,<br/>modelName, modelType)
Handler->>Service: SetTenantDefaultModels(...)
Service->>Service: checkModelAvailable(...)
Service->>DAOs: Verify provider/instance/model<br/>existence and compatibility
DAOs->>ProviderMgr: GetModelProviderManager()
ProviderMgr-->>DAOs: Model schema metadata
DAOs-->>Service: Validation result
Service->>DB: Update tenant record<br/>with formatted model string
DB-->>Service: Success
Service-->>Handler: Response
Handler-->>CLI: 200 OK
end
rect rgba(150, 200, 100, 0.5)
Note over CLI,DB: List Tenant Default Models
CLI->>Handler: GET /api/v1/models
Handler->>Service: ListTenantDefaultModels(userID)
Service->>DAOs: Fetch tenant info
DAOs-->>Service: Tenant record
loop For each model type (chat, embedding, rerank, asr, image2text, tts)
Service->>Service: GetModelInfo(tenantID,<br/>defaultModel, modelType)
Service->>DAOs: Parse and validate<br/>provider/instance/model
DAOs-->>Service: Model details & availability
end
Service-->>Handler: []ModelItem
Handler-->>CLI: 200 OK + models list
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Suggested labels
Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Comment |
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (1)
internal/cli/user_parser.go (1)
1600-1642: Centralize the model-type mapping.This parser now hardcodes the alias-to-internal-type map again, and the duplication has already drifted:
parseResetCommandin this file still usesreranker_id, whileinternal/service/tenant.gomaps the same type torerank_id. A shared helper/map would keep set/list/reset flows aligned.🤖 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 1600 - 1642, Extract the hardcoded alias-to-internal-type mapping used in this switch (the modelType assignment in this parser) into a single shared helper or exported map (e.g., ModelTypeMap or MapModelTokenToType) in a common package and replace the switch in this function with a lookup call; update parseResetCommand and internal/service/tenant.go to use that same helper so the keys (e.g., the rerank/reranker alias and the final internal key like rerank_id or reranker_id) are consistent across set/list/reset flows, and return the same error when an unknown token is encountered.
🤖 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/router/router.go`:
- Around line 222-225: Routes for the models collection are registered with
trailing "/" which creates endpoints at "/models/" and mismatches client calls
to "/models"; update the registrations in router.go so the model group uses
empty relative paths (e.g. replace GET("/") and PATCH("/") with GET("") and
PATCH("")) when binding r.tenantHandler.GetModels and r.tenantHandler.SetModels
to ensure exact path alignment with the client.
In `@internal/service/tenant.go`:
- Around line 374-385: The code sets enable based on modelEntity == nil which
inverts the flag; change the logic in the block that calls
s.modelDAO.GetModelByProviderIDAndInstanceIDAndModelName so that enable is true
when a tenant-model row exists (modelEntity != nil) and false when it does not
(nil after handling the "record not found" case); keep the same error handling
around GetModelByProviderIDAndInstanceIDAndModelName and only flip the boolean
assignment for the variable enable.
- Around line 510-552: SetTenantDefaultModels currently writes only the string
default (llm_id/embd_id/rerank_id/...) via tenantDAO.Update, but leaves the
paired numeric foreign key column (tenant_llm_id, tenant_embd_id,
tenant_rerank_id, etc.) stale; update this function to write both columns in the
same tenantDAO.Update call (e.g., set modelTypeID and the corresponding
tenant_*_id) or call/reuse EnsureTenantModelIDForParams to compute and persist
the numeric tenant_*_id alongside the default string so both fields are kept in
sync when changing the default.
- Around line 403-471: The code currently ignores errors from s.GetModelInfo and
silently omits broken defaults; change each GetModelInfo call (for LLMID,
EmbDID, RerankID, ASRID, Img2TxtID and TTSID) to propagate errors instead of
swallowing them—i.e., after calling s.GetModelInfo(...) check if err != nil and
return nil, fmt.Errorf("GetModelInfo failed for tenant %s id %v type %s: %w",
ownedTenant.TenantID, <the id variable>, "<type>", err) so the API surfaces
corrupted defaults rather than hiding them; ensure you update all branches
including the TTSID optional path and keep existing successful append logic for
ModelItem.
- Around line 497-505: The branch incorrectly dereferences err when err may be
nil; change the logic around the call to
s.modelDAO.GetModelByProviderIDAndInstanceIDAndModelName so you first check for
a non-nil err (handle the "record not found" case and real errors there), and
only then inspect modelEntity; e.g. after calling
GetModelByProviderIDAndInstanceIDAndModelName, if err != nil { if err.Error() ==
"record not found" { return nil } return fmt.Errorf("model %s isn't available",
modelName) } else if modelEntity == nil { return nil } so you never call
err.Error() on a nil err and correctly handle found/not-found/error paths.
---
Nitpick comments:
In `@internal/cli/user_parser.go`:
- Around line 1600-1642: Extract the hardcoded alias-to-internal-type mapping
used in this switch (the modelType assignment in this parser) into a single
shared helper or exported map (e.g., ModelTypeMap or MapModelTokenToType) in a
common package and replace the switch in this function with a lookup call;
update parseResetCommand and internal/service/tenant.go to use that same helper
so the keys (e.g., the rerank/reranker alias and the final internal key like
rerank_id or reranker_id) are consistent across set/list/reset flows, and return
the same error when an unknown token is encountered.
🪄 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: 80fa1b38-3ac0-48c1-a688-6904006bae3a
📒 Files selected for processing (8)
conf/models/zhipu-ai.jsoninternal/cli/client.gointernal/cli/common_command.gointernal/cli/user_parser.gointernal/entity/model.gointernal/handler/tenant.gointernal/router/router.gointernal/service/tenant.go
| model := v1.Group("/models") | ||
| { | ||
| model.GET("/", r.tenantHandler.GetModels) | ||
| model.PATCH("/", r.tenantHandler.SetModels) |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
# First, locate and examine the router file
fd -e go -path "*router*" | head -20Repository: infiniflow/ragflow
Length of output: 230
🏁 Script executed:
# Get the specific lines from router.go
if [ -f "internal/router/router.go" ]; then
wc -l internal/router/router.go
fiRepository: infiniflow/ragflow
Length of output: 91
🏁 Script executed:
# Find common_command.go
fd -e go "common_command"Repository: infiniflow/ragflow
Length of output: 92
🏁 Script executed:
# Read lines around 222-225 in router.go
sed -n '215,235p' internal/router/router.goRepository: infiniflow/ragflow
Length of output: 998
🏁 Script executed:
# Search for model-related requests in common_command.go
rg -n "models" internal/cli/common_command.go -B 2 -A 2Repository: infiniflow/ragflow
Length of output: 1874
🏁 Script executed:
# Search for v1 group definition in router.go
sed -n '1,230p' internal/router/router.go | grep -n "v1 :=" -A 5Repository: infiniflow/ragflow
Length of output: 237
🏁 Script executed:
# Search for HTTPClient definition and URL construction
rg -n "HTTPClient" internal/cli/common_command.go -B 3 -A 3 | head -40Repository: infiniflow/ragflow
Length of output: 1037
🏁 Script executed:
# Find HTTPClient implementation
fd -e go | xargs rg -l "func.*HTTPClient" | head -10Repository: infiniflow/ragflow
Length of output: 249
🏁 Script executed:
# Examine the HTTPClient Request method implementation
cat -n internal/cli/http_client.go | head -150Repository: infiniflow/ragflow
Length of output: 4958
🏁 Script executed:
# Let me verify the complete http_client.go file to ensure there's no trailing slash normalization
wc -l internal/cli/http_client.goRepository: infiniflow/ragflow
Length of output: 93
🏁 Script executed:
# Check if there's any trailing slash normalization in the request path
tail -50 internal/cli/http_client.goRepository: infiniflow/ragflow
Length of output: 1350
Register collection routes without trailing slashes to match client calls.
Routes at lines 224-225 register with GET("/") and PATCH("/"), which create endpoints at /api/v1/models/. However, internal/cli/common_command.go calls GET /models and PATCH /models at lines 424 and 402 respectively. This mismatch makes the feature depend on Gin's trailing-slash redirect behavior for both read and write requests. Use empty relative paths to ensure exact alignment.
Suggested fix
model := v1.Group("/models")
{
- model.GET("/", r.tenantHandler.GetModels)
- model.PATCH("/", r.tenantHandler.SetModels)
+ model.GET("", r.tenantHandler.GetModels)
+ model.PATCH("", r.tenantHandler.SetModels)
}📝 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.
| model := v1.Group("/models") | |
| { | |
| model.GET("/", r.tenantHandler.GetModels) | |
| model.PATCH("/", r.tenantHandler.SetModels) | |
| model := v1.Group("/models") | |
| { | |
| model.GET("", r.tenantHandler.GetModels) | |
| model.PATCH("", r.tenantHandler.SetModels) | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/router/router.go` around lines 222 - 225, Routes for the models
collection are registered with trailing "/" which creates endpoints at
"/models/" and mismatches client calls to "/models"; update the registrations in
router.go so the model group uses empty relative paths (e.g. replace GET("/")
and PATCH("/") with GET("") and PATCH("")) when binding
r.tenantHandler.GetModels and r.tenantHandler.SetModels to ensure exact path
alignment with the client.
| var modelEntity *entity.TenantModel | ||
| modelEntity, err = s.modelDAO.GetModelByProviderIDAndInstanceIDAndModelName(modelProvider.ID, modelInstance.ID, *modelName) | ||
| if err != nil { | ||
| errString := err.Error() | ||
| if !strings.Contains(errString, "record not found") { | ||
| return nil, nil, nil, false, err | ||
| } | ||
| } | ||
|
|
||
| enable := modelEntity == nil | ||
|
|
||
| return providerName, instanceName, modelName, enable, nil |
There was a problem hiding this comment.
Enable is inverted for resolved defaults.
Once the tenant-model row is found, this sets Enable to false because it uses modelEntity == nil. That makes list default models report configured models as disabled. The flag should be derived from the presence of the resolved tenant-model row, not its absence.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/service/tenant.go` around lines 374 - 385, The code sets enable
based on modelEntity == nil which inverts the flag; change the logic in the
block that calls s.modelDAO.GetModelByProviderIDAndInstanceIDAndModelName so
that enable is true when a tenant-model row exists (modelEntity != nil) and
false when it does not (nil after handling the "record not found" case); keep
the same error handling around GetModelByProviderIDAndInstanceIDAndModelName and
only flip the boolean assignment for the variable enable.
| defaultChatModelProvider, defaultChatModelInstance, defaultChatModelName, defaultChatModelEnable, err := s.GetModelInfo(ownedTenant.TenantID, ownedTenant.LLMID, "chat") | ||
| if err == nil { | ||
| result = append(result, ModelItem{ | ||
| ModelProvider: defaultChatModelProvider, | ||
| ModelInstance: defaultChatModelInstance, | ||
| ModelName: defaultChatModelName, | ||
| ModelType: "llm", | ||
| Enable: defaultChatModelEnable, | ||
| }) | ||
| } | ||
|
|
||
| defaultEmbeddingModelProvider, defaultEmbeddingModelInstance, defaultEmbeddingModelName, defaultEmbeddingModelEnable, err := s.GetModelInfo(ownedTenant.TenantID, ownedTenant.EmbDID, "embedding") | ||
| if err == nil { | ||
| result = append(result, ModelItem{ | ||
| ModelProvider: defaultEmbeddingModelProvider, | ||
| ModelInstance: defaultEmbeddingModelInstance, | ||
| ModelName: defaultEmbeddingModelName, | ||
| ModelType: "embedding", | ||
| Enable: defaultEmbeddingModelEnable, | ||
| }) | ||
| } | ||
|
|
||
| defaultRerankModelProvider, defaultRerankModelInstance, defaultRerankModelName, defaultRerankModelEnable, err := s.GetModelInfo(ownedTenant.TenantID, ownedTenant.RerankID, "rerank") | ||
| if err == nil { | ||
| result = append(result, ModelItem{ | ||
| ModelProvider: defaultRerankModelProvider, | ||
| ModelInstance: defaultRerankModelInstance, | ||
| ModelName: defaultRerankModelName, | ||
| ModelType: "rerank", | ||
| Enable: defaultRerankModelEnable, | ||
| }) | ||
| } | ||
|
|
||
| defaultASRModelProvider, defaultASRModelInstance, defaultASRModelName, defaultASREnable, err := s.GetModelInfo(ownedTenant.TenantID, ownedTenant.ASRID, "asr") | ||
| if err == nil { | ||
| result = append(result, ModelItem{ | ||
| ModelProvider: defaultASRModelProvider, | ||
| ModelInstance: defaultASRModelInstance, | ||
| ModelName: defaultASRModelName, | ||
| ModelType: "asr", | ||
| Enable: defaultASREnable, | ||
| }) | ||
| } | ||
|
|
||
| defaultImage2TextModelProvider, defaultImage2TextModelInstance, defaultImage2TextModelName, defaultImage2TextModelEnable, err := s.GetModelInfo(ownedTenant.TenantID, ownedTenant.Img2TxtID, "image2text") | ||
| if err == nil { | ||
| result = append(result, ModelItem{ | ||
| ModelProvider: defaultImage2TextModelProvider, | ||
| ModelInstance: defaultImage2TextModelInstance, | ||
| ModelName: defaultImage2TextModelName, | ||
| ModelType: "image2text", | ||
| Enable: defaultImage2TextModelEnable, | ||
| }) | ||
| } | ||
|
|
||
| if ownedTenant.TTSID == nil { | ||
| return result, nil | ||
| } | ||
|
|
||
| defaultTTSModelProvider, defaultTTSModelInstance, defaultTTSModelName, defaultTTSModelEnable, err := s.GetModelInfo(ownedTenant.TenantID, *ownedTenant.TTSID, "tts") | ||
| if err == nil { | ||
| result = append(result, ModelItem{ | ||
| ModelProvider: defaultTTSModelProvider, | ||
| ModelInstance: defaultTTSModelInstance, | ||
| ModelName: defaultTTSModelName, | ||
| ModelType: "tts", | ||
| Enable: defaultTTSModelEnable, | ||
| }) | ||
| } |
There was a problem hiding this comment.
Don't silently drop broken defaults from the list response.
Each default is appended only when GetModelInfo returns nil. If a stored default points to a deleted provider, instance, or model, the endpoint just omits that row and still returns success. That turns corrupted state into “not set” and makes troubleshooting much harder.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/service/tenant.go` around lines 403 - 471, The code currently
ignores errors from s.GetModelInfo and silently omits broken defaults; change
each GetModelInfo call (for LLMID, EmbDID, RerankID, ASRID, Img2TxtID and TTSID)
to propagate errors instead of swallowing them—i.e., after calling
s.GetModelInfo(...) check if err != nil and return nil, fmt.Errorf("GetModelInfo
failed for tenant %s id %v type %s: %w", ownedTenant.TenantID, <the id
variable>, "<type>", err) so the API surfaces corrupted defaults rather than
hiding them; ensure you update all branches including the TTSID optional path
and keep existing successful append logic for ModelItem.
| var modelEntity *entity.TenantModel | ||
| modelEntity, err = s.modelDAO.GetModelByProviderIDAndInstanceIDAndModelName(modelProvider.ID, modelInstance.ID, modelName) | ||
| if err != nil || modelEntity != nil { | ||
| var errString = err.Error() | ||
| if errString == "record not found" { | ||
| return nil | ||
| } | ||
| return fmt.Errorf("model %s isn't available", modelName) | ||
| } |
There was a problem hiding this comment.
Avoid dereferencing err on the success path.
When GetModelByProviderIDAndInstanceIDAndModelName returns (modelEntity != nil, err == nil), this branch still executes and line 500 calls err.Error(), which will panic. Split the found, not found, and real-error paths before inspecting the error.
Suggested fix
var modelEntity *entity.TenantModel
modelEntity, err = s.modelDAO.GetModelByProviderIDAndInstanceIDAndModelName(modelProvider.ID, modelInstance.ID, modelName)
- if err != nil || modelEntity != nil {
- var errString = err.Error()
- if errString == "record not found" {
- return nil
- }
- return fmt.Errorf("model %s isn't available", modelName)
+ if err != nil {
+ if strings.Contains(err.Error(), "record not found") {
+ return fmt.Errorf("model %s isn't available", modelName)
+ }
+ return err
}
+ if modelEntity == nil {
+ return fmt.Errorf("model %s isn't available", modelName)
+ }
return 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.
| var modelEntity *entity.TenantModel | |
| modelEntity, err = s.modelDAO.GetModelByProviderIDAndInstanceIDAndModelName(modelProvider.ID, modelInstance.ID, modelName) | |
| if err != nil || modelEntity != nil { | |
| var errString = err.Error() | |
| if errString == "record not found" { | |
| return nil | |
| } | |
| return fmt.Errorf("model %s isn't available", modelName) | |
| } | |
| var modelEntity *entity.TenantModel | |
| modelEntity, err = s.modelDAO.GetModelByProviderIDAndInstanceIDAndModelName(modelProvider.ID, modelInstance.ID, modelName) | |
| if err != nil { | |
| if strings.Contains(err.Error(), "record not found") { | |
| return fmt.Errorf("model %s isn't available", modelName) | |
| } | |
| return err | |
| } | |
| if modelEntity == nil { | |
| return fmt.Errorf("model %s isn't available", modelName) | |
| } | |
| return nil | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/service/tenant.go` around lines 497 - 505, The branch incorrectly
dereferences err when err may be nil; change the logic around the call to
s.modelDAO.GetModelByProviderIDAndInstanceIDAndModelName so you first check for
a non-nil err (handle the "record not found" case and real errors there), and
only then inspect modelEntity; e.g. after calling
GetModelByProviderIDAndInstanceIDAndModelName, if err != nil { if err.Error() ==
"record not found" { return nil } return fmt.Errorf("model %s isn't available",
modelName) } else if modelEntity == nil { return nil } so you never call
err.Error() on a nil err and correctly handle found/not-found/error paths.
| func (s *TenantService) SetTenantDefaultModels(userID, modelProvider, modelInstance, modelName, modelType string) error { | ||
|
|
||
| tenantInfos, err := s.tenantDAO.GetInfoByUserID(userID) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| if len(tenantInfos) == 0 { | ||
| return nil // No tenant found (should not happen for valid user) | ||
| } | ||
|
|
||
| ownedTenant := tenantInfos[0] | ||
| err = s.checkModelAvailable(ownedTenant.TenantID, modelProvider, modelInstance, modelName, modelType) | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| var modelTypeID string | ||
| if modelType == "chat" { | ||
| modelTypeID = "llm_id" | ||
| } | ||
| if modelType == "embedding" { | ||
| modelTypeID = "embd_id" | ||
| } | ||
| if modelType == "rerank" { | ||
| modelTypeID = "rerank_id" | ||
| } | ||
| if modelType == "asr" { | ||
| modelTypeID = "asr_id" | ||
| } | ||
| if modelType == "image2text" { | ||
| modelTypeID = "img2txt_id" | ||
| } | ||
| if modelType == "tts" { | ||
| modelTypeID = "tts_id" | ||
| } | ||
| if modelTypeID == "" { | ||
| return fmt.Errorf("model type %s is invalid", modelType) | ||
| } | ||
|
|
||
| defaultModel := fmt.Sprintf("%s@%s@%s", modelName, modelInstance, modelProvider) | ||
| err = s.tenantDAO.Update(ownedTenant.TenantID, map[string]interface{}{ | ||
| modelTypeID: defaultModel, | ||
| }) |
There was a problem hiding this comment.
Keep the paired tenant_*_id column in sync with the default string.
This updates only llm_id/embd_id/rerank_id/… even though the tenant row also stores the paired numeric foreign key (tenant_llm_id, tenant_embd_id, etc.). After a default switch, downstream code can still observe the old model ID. Update both columns in the same write, or reuse EnsureTenantModelIDForParams here.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/service/tenant.go` around lines 510 - 552, SetTenantDefaultModels
currently writes only the string default (llm_id/embd_id/rerank_id/...) via
tenantDAO.Update, but leaves the paired numeric foreign key column
(tenant_llm_id, tenant_embd_id, tenant_rerank_id, etc.) stale; update this
function to write both columns in the same tenantDAO.Update call (e.g., set
modelTypeID and the corresponding tenant_*_id) or call/reuse
EnsureTenantModelIDForParams to compute and persist the numeric tenant_*_id
alongside the default string so both fields are kept in sync when changing the
default.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14191 +/- ##
=======================================
Coverage 96.66% 96.66%
=======================================
Files 10 10
Lines 690 690
Branches 108 108
=======================================
Hits 667 667
Misses 8 8
Partials 15 15 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
### What problem does this PR solve? ``` RAGFlow(user)> set default vlm "zhipu-ai" "ccc" "glm-4.6v-flash"; SUCCESS RAGFlow(user)> list default models; +--------+----------------+----------------+----------------+------------+ | enable | model_instance | model_name | model_provider | model_type | +--------+----------------+----------------+----------------+------------+ | true | ccc | glm-4.6v-flash | zhipu-ai | llm | | true | ccc | glm-4.6v-flash | zhipu-ai | image2text | +--------+----------------+----------------+----------------+------------+ ``` ### Type of change - [x] New Feature (non-breaking change which adds functionality) Signed-off-by: Jin Hai <[email protected]>
What problem does this PR solve?
Type of change