Skip to content

Go: set and list default models - #14191

Merged
JinHai-CN merged 1 commit into
infiniflow:mainfrom
JinHai-CN:fix389
Apr 17, 2026
Merged

JinHai-CN merged 1 commit into
infiniflow:mainfrom
JinHai-CN:fix389

Conversation

@JinHai-CN

Copy link
Copy Markdown
Member

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

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

@JinHai-CN JinHai-CN self-assigned this Apr 17, 2026
@coderabbitai

coderabbitai Bot commented Apr 17, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Added support for a new AI model (glm-4.6v-Flash) with 128k token capacity and implemented tenant-level default model management. Changes span configuration, CLI commands, API endpoints, and service layer validation logic with model provider and instance validation.

Changes

Cohort / File(s) Summary
Model Configuration
conf/models/zhipu-ai.json
Added new glm-4.6v-Flash model with max_tokens: 128000, supporting chat and image2text capabilities.
CLI Layer
internal/cli/client.go, internal/cli/common_command.go, internal/cli/user_parser.go
Added set_default_model and list_user_default_models command routing; implemented corresponding client methods with request validation and error handling; updated parser to handle three-part model identifier (provider/instance/name) with mapped model type strings.
Entity Layer
internal/entity/model.go
Changed Provider.Models from value slice ([]Model) to pointer slice ([]*Model), updating related ProviderManager.findModel lookup logic.
API Layer
internal/handler/tenant.go, internal/router/router.go
Added GetModels and SetModels handler endpoints with SetModelRequest payload type; registered new /api/v1/models routes for GET and PATCH operations.
Service Layer
internal/service/tenant.go
Injected model-related DAOs; introduced ModelItem and DefaultModelResponse types; implemented GetModelInfo, ListTenantDefaultModels, SetTenantDefaultModels, and checkModelAvailable methods with model validation and tenant record persistence.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Suggested labels

size:M

Poem

🐰 A flash of wisdom in model selection,
Three parts form a perfect collection—
Provider, instance, name aligned,
Default models by tenant designed.
Validation hops through layers deep,
While rabbit code our configs keep! 🌟

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Go: set and list default models' directly summarizes the main changes, which add functionality to set and list default models across multiple files.
Description check ✅ Passed The PR description includes both required template sections: a concrete problem statement with example CLI usage and output, and the feature classification correctly marked.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ 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 17, 2026
@JinHai-CN JinHai-CN removed their assignment Apr 17, 2026
@JinHai-CN
JinHai-CN marked this pull request as ready for review April 17, 2026 07:22
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Apr 17, 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: 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: parseResetCommand in this file still uses reranker_id, while internal/service/tenant.go maps the same type to rerank_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

📥 Commits

Reviewing files that changed from the base of the PR and between 28d8b1c and c1c179f.

📒 Files selected for processing (8)
  • conf/models/zhipu-ai.json
  • internal/cli/client.go
  • internal/cli/common_command.go
  • internal/cli/user_parser.go
  • internal/entity/model.go
  • internal/handler/tenant.go
  • internal/router/router.go
  • internal/service/tenant.go

Comment thread internal/router/router.go
Comment on lines +222 to +225
model := v1.Group("/models")
{
model.GET("/", r.tenantHandler.GetModels)
model.PATCH("/", r.tenantHandler.SetModels)

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:

# First, locate and examine the router file
fd -e go -path "*router*" | head -20

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

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

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

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

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

Repository: infiniflow/ragflow

Length of output: 1037


🏁 Script executed:

# Find HTTPClient implementation
fd -e go | xargs rg -l "func.*HTTPClient" | head -10

Repository: infiniflow/ragflow

Length of output: 249


🏁 Script executed:

# Examine the HTTPClient Request method implementation
cat -n internal/cli/http_client.go | head -150

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

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

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

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

Comment on lines +374 to +385
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

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

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.

Comment on lines +403 to +471
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,
})
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Don't 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.

Comment on lines +497 to +505
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)
}

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

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.

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

Comment on lines +510 to +552
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,
})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Keep the 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

codecov Bot commented Apr 17, 2026 •

Copy link
Copy Markdown

Codecov Report

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

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.
📢 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 9410664 into infiniflow:main Apr 17, 2026
1 check passed
@coderabbitai coderabbitai Bot mentioned this pull request Apr 20, 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)> 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 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