Repository navigation
GO: improve model info parsing and add model_id/tenant context to list response - #16804
Conversation
📝 WalkthroughWalkthroughTenant-scoped model identifiers are added to tenant metadata, default-model handling, chat and dataset persistence, and centralized provider resolution. Model consumers migrate to the new resolver APIs, with updated parsing, validation, owner-tenant listing, and coverage tests. ChangesTenant model contracts and defaults
Central model resolution
Chat tenant model IDs
Dataset and runtime consumers
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant Client
participant ChatService
participant ModelProviderService
participant TenantDAO
Client->>ChatService: Create or update chat with model references
ChatService->>ModelProviderService: ResolveModelID and ResolveModelConfig
ModelProviderService->>TenantDAO: Read tenant model and provider records
TenantDAO-->>ModelProviderService: Tenant-scoped model metadata
ModelProviderService-->>ChatService: Resolved IDs and API configuration
ChatService-->>Client: Persisted chat response
Possibly related PRs
Suggested labels: Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
internal/service/dataset.go (1)
3599-3611: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueDead/redundant branches in
validateDatasetEmbeddingModel.After the
!strings.Contains(embeddingModel, "@")early-return,strings.Splitalways yields ≥2 parts, solen(parts) < 2(Line 3609) is unreachable, and the trailingparts[0]/parts[len-1]empty check (Line 3612) is already covered by the loop that rejects any empty segment.♻️ Suggested simplification
parts := strings.Split(embeddingModel, "@") for _, part := range parts { if strings.TrimSpace(part) == "" { return errors.New("Both model_name and provider must be non-empty strings") } } - if len(parts) < 2 { - return errors.New("Embedding model identifier must follow <model_name>@<provider> format") - } - if strings.TrimSpace(parts[0]) == "" || strings.TrimSpace(parts[len(parts)-1]) == "" { - return errors.New("Both model_name and provider must be non-empty strings") - } - return nil🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/service/dataset.go` around lines 3599 - 3611, Remove the unreachable len(parts) < 2 validation and any redundant trailing first/last-part empty checks from validateDatasetEmbeddingModel; retain the existing split and loop validation for empty segments after the @ early return.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/service/dataset.go`:
- Around line 2481-2488: Align ResolveModelID error handling between
CreateDataset and UpdateDataset: choose the same reject-or-fallback behavior and
apply it consistently when resolving the tenant default embedding model,
including the branch assigning tenantEmbdID. Also simplify
validateDatasetEmbeddingModel by removing the unreachable len(parts) < 2 check
after the “@” guard and consolidating overlapping empty-segment validation.
In `@internal/service/model_service.go`:
- Around line 2317-2327: ResolveModelConfig currently passes tenantID to
GetModelConfigByID, but the shared-provider authorization path expects a user
ID. Update ResolveModelConfig and its callers or context to receive/use the
authenticated user ID, then pass that value to GetModelConfigByID while
preserving tenant scoping for provider-instance resolution.
In `@internal/service/tenant.go`:
- Around line 788-793: Check the error returned by tenantDAO.Update in the
surrounding tenant update function and return it immediately when non-nil
instead of unconditionally returning nil, preserving successful nil behavior.
---
Nitpick comments:
In `@internal/service/dataset.go`:
- Around line 3599-3611: Remove the unreachable len(parts) < 2 validation and
any redundant trailing first/last-part empty checks from
validateDatasetEmbeddingModel; retain the existing split and loop validation for
empty segments after the @ early return.
🪄 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: c5fce3ed-5a23-40fc-a115-936bb520e0e1
📒 Files selected for processing (17)
internal/dao/tenant.gointernal/entity/types.gointernal/handler/providers.gointernal/ingestion/component/pdf_vision_dispatch.gointernal/service/chat.gointernal/service/chat_pipeline.gointernal/service/chat_rest_update_test.gointernal/service/chunk/chunk.gointernal/service/dataset.gointernal/service/dataset_update_test.gointernal/service/generator.gointernal/service/memory.gointernal/service/memory_message_service.gointernal/service/model_service.gointernal/service/model_service_test.gointernal/service/tenant.gointernal/service/tenant_test.go
| if embdID != "" && tenantEmbdID == "" { | ||
| resolvedID, err := NewModelProviderService().ResolveModelID(tenantID, entity.ModelTypeEmbedding, embdID) | ||
| if err == nil { | ||
| tenantEmbdID = resolvedID | ||
| } else { | ||
| return nil, common.CodeDataError, err | ||
| } | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
ast-grep run --pattern 'func ($_ $_) ResolveModelID($$$) $_' --lang go internal/service/model_service.go
rg -nP 'tenant\.EmbdID|TenantEmbdID' internal/service/dataset.goRepository: infiniflow/ragflow
Length of output: 4112
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Show the create and update call sites with line numbers.
sed -n '2460,2525p' internal/service/dataset.go | cat -n
printf '\n----\n'
sed -n '2785,2835p' internal/service/dataset.go | cat -n
printf '\n----\n'
sed -n '3588,3635p' internal/service/dataset.go | cat -nRepository: infiniflow/ragflow
Length of output: 6077
🏁 Script executed:
#!/bin/bash
set -euo pipefail
python3 - <<'PY'
from pathlib import Path
text = Path('internal/service/dataset.go').read_text()
start = text.index('func validateDatasetEmbeddingModel')
end = text.index('func ', start + 1)
print(text[start:end])
PYRepository: infiniflow/ragflow
Length of output: 1104
🏁 Script executed:
#!/bin/bash
set -euo pipefail
rg -n "tenantEmbdID|embdID" internal/service/dataset.goRepository: infiniflow/ragflow
Length of output: 1994
Align ResolveModelID handling in create and update
CreateDatasetfails when the tenant defaultEmbdIDcan’t be resolved, butUpdateDatasetignores the sameResolveModelIDerror and continues with an emptytenant_embd_id.- That makes dataset creation fail for tenants whose default embedding model isn’t mapped, while updates still succeed; either both paths should reject or both should fall back.
- Separately,
validateDatasetEmbeddingModelhas an unreachablelen(parts) < 2branch after theContains("@")guard, and the outer/inner empty-segment checks overlap.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/service/dataset.go` around lines 2481 - 2488, Align ResolveModelID
error handling between CreateDataset and UpdateDataset: choose the same
reject-or-fallback behavior and apply it consistently when resolving the tenant
default embedding model, including the branch assigning tenantEmbdID. Also
simplify validateDatasetEmbeddingModel by removing the unreachable len(parts) <
2 check after the “@” guard and consolidating overlapping empty-segment
validation.
| func (m *ModelProviderService) ResolveModelConfig(tenantID string, modelType entity.ModelType, modelRef string) (modelModule.ModelDriver, string, *modelModule.APIConfig, int, error) { | ||
| if strings.TrimSpace(modelRef) == "" { | ||
| return nil, "", nil, 0, fmt.Errorf("model ref is required") | ||
| } | ||
| if _, err := m.modelDAO.GetByID(modelRef); err == nil { | ||
| return m.GetModelConfigByID(tenantID, modelType, modelRef) | ||
| } else if !errors.Is(err, gorm.ErrRecordNotFound) { | ||
| return nil, "", nil, 0, err | ||
| } | ||
| return m.GetModelConfigFromProviderInstance(tenantID, modelType, modelRef) | ||
| } |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Inspect all callers of GetModelConfigByID and ResolveModelConfig to see whether a tenantID or userID is passed
rg -nP --type=go -C2 '\b(GetModelConfigByID|ResolveModelConfig)\s*\(' internal
# Confirm GetUserTenantRelationByUserID expects a user ID
ast-grep run --pattern 'func ($_ $_) GetUserTenantRelationByUserID($$$) { $$$ }' --lang go internalRepository: infiniflow/ragflow
Length of output: 15870
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect the implementation around GetModelConfigByID and the relation lookup it uses.
sed -n '2204,2255p' internal/service/model_service.go
printf '\n---\n'
rg -n "func .*GetUserTenantRelationByUserID|GetUserTenantRelationByUserID\\(" internal -g '*.go' -C 3Repository: infiniflow/ragflow
Length of output: 5020
Use the user ID here, not the tenant ID ResolveModelConfig passes tenantID into GetModelConfigByID, but that method falls back to GetUserTenantRelationByUserID(userID) when the provider belongs to another tenant. That makes the shared-provider path authorize with a tenant ID where a user ID is expected, so cross-tenant model access can be rejected.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/service/model_service.go` around lines 2317 - 2327,
ResolveModelConfig currently passes tenantID to GetModelConfigByID, but the
shared-provider authorization path expects a user ID. Update ResolveModelConfig
and its callers or context to receive/use the authenticated user ID, then pass
that value to GetModelConfigByID while preserving tenant scoping for
provider-instance resolution.
| err = s.tenantDAO.Update(ownedTenant.TenantID, map[string]interface{}{ | ||
| modelTypeID: defaultModel, | ||
| modelTypeID: defaultModel, | ||
| tenantModelTypeID: tenantModelID, | ||
| }) | ||
|
|
||
| return nil |
There was a problem hiding this comment.
🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win
Ignored Update error causes silent persistence failures.
err from tenantDAO.Update is assigned but never checked; the function unconditionally returns nil. A failed DB write is reported as success to the caller, so the tenant default model / tenant model ID may not persist while the API responds OK.
🐛 Return the update error
- err = s.tenantDAO.Update(ownedTenant.TenantID, map[string]interface{}{
- modelTypeID: defaultModel,
- tenantModelTypeID: tenantModelID,
- })
-
- return nil
+ return s.tenantDAO.Update(ownedTenant.TenantID, map[string]interface{}{
+ modelTypeID: defaultModel,
+ tenantModelTypeID: tenantModelID,
+ })📝 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.
| err = s.tenantDAO.Update(ownedTenant.TenantID, map[string]interface{}{ | |
| modelTypeID: defaultModel, | |
| modelTypeID: defaultModel, | |
| tenantModelTypeID: tenantModelID, | |
| }) | |
| return nil | |
| return s.tenantDAO.Update(ownedTenant.TenantID, map[string]interface{}{ | |
| modelTypeID: defaultModel, | |
| tenantModelTypeID: tenantModelID, | |
| }) |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/service/tenant.go` around lines 788 - 793, Check the error returned
by tenantDAO.Update in the surrounding tenant update function and return it
immediately when non-nil instead of unconditionally returning nil, preserving
successful nil behavior.
Summary
Improve model resolution throughout the Go service layer by adding proper
model_id(DB UUID) tracking alongside the existingllm_id(logical modelreference). This fixes parsing edge cases and enables multi-tenant model
listing.
Changes
Model info parsing (
internal/service/tenant.go)ModelIDfield toModelItemstruct, populated for all model typesGetModelInfomodel name parsing: support@in model names(previously broke on model names containing
@by assuming exactly 3 parts;now joins leading segments with
@and extracts provider/instance from thelast two)
factoryModelTypeNameto normalizeimage2text→visionModel list API (
internal/service/model_service.go)ListTenantAddedModelsnow accepts an explicitownerTenantIDparameter;falls back to the user's first owned tenant when empty
model_id,tenant_id,tenant_name— the front endneeds these to link models back to their owning tenant
resolveModelListTenantwith permission validationChat creation (
internal/service/chat.go)validateCreateLLMID→resolveCreateLLMID: returnstenant_llm_idinsteadof only validating; same for rerank
tenant_llm_id/tenant_rerank_idthrough the chat create flowDataset service (
internal/service/dataset.go)GetModelConfigFromProviderInstance→ResolveModelConfigtenant_embd_idon dataset creation so the dataset tracks thetenant-model relationship
PDF vision dispatch (
internal/ingestion/component/pdf_vision_dispatch.go)resolveModelConfigtries model DB ID first, falls back to provider+instanceresolveModelConfigByIDandtenantModelIDByTypehelpersTenantLLMID-style tenant model referencesMisc
tenantDAOtoModelProviderServicemodel_idfields