Skip to content

GO: improve model info parsing and add model_id/tenant context to list response - #16804

Merged
wangq8 merged 1 commit into
infiniflow:mainfrom
buua436:b105
Jul 10, 2026
Merged

wangq8 merged 1 commit into
infiniflow:mainfrom
buua436:b105

Conversation

@buua436

@buua436 buua436 commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

Summary

Improve model resolution throughout the Go service layer by adding proper
model_id (DB UUID) tracking alongside the existing llm_id (logical model
reference). This fixes parsing edge cases and enables multi-tenant model
listing.

Changes

Model info parsing (internal/service/tenant.go)

  • Add ModelID field to ModelItem struct, populated for all model types
  • Fix GetModelInfo model 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 the
    last two)
  • Add factoryModelTypeName to normalize image2text → vision
  • Only return active models (skip inactive/disabled entries)

Model list API (internal/service/model_service.go)

  • ListTenantAddedModels now accepts an explicit ownerTenantID parameter;
    falls back to the user's first owned tenant when empty
  • Response now includes model_id, tenant_id, tenant_name — the front end
    needs these to link models back to their owning tenant
  • Add resolveModelListTenant with permission validation

Chat creation (internal/service/chat.go)

  • validateCreateLLMID → resolveCreateLLMID: returns tenant_llm_id instead
    of only validating; same for rerank
  • Propagate tenant_llm_id / tenant_rerank_id through the chat create flow

Dataset service (internal/service/dataset.go)

  • Rename GetModelConfigFromProviderInstance → ResolveModelConfig
  • Resolve tenant_embd_id on dataset creation so the dataset tracks the
    tenant-model relationship

PDF vision dispatch (internal/ingestion/component/pdf_vision_dispatch.go)

  • resolveModelConfig tries model DB ID first, falls back to provider+instance
  • Add resolveModelConfigByID and tenantModelIDByType helpers
  • Vision model resolution prefers TenantLLMID-style tenant model references

Misc

  • Add tenantDAO to ModelProviderService
  • Update tests for the new signatures and model_id fields

@coderabbitai

coderabbitai Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

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

Changes

Tenant model contracts and defaults

Layer / File(s) Summary
Tenant metadata and default-model handling
internal/dao/tenant.go, internal/entity/types.go, internal/service/tenant.go
Tenant responses expose nullable tenant model IDs, vision maps to image-to-text, model defaults include model IDs, and availability requires active compatible tenant models.
Owner-tenant model listing
internal/handler/providers.go, internal/service/model_service.go
Added-model listing accepts owner_tenant_id, resolves the permitted tenant, and returns tenant metadata, active model IDs, and API model-type names.

Central model resolution

Layer / File(s) Summary
Unified provider and tenant resolution
internal/service/model_service.go, internal/ingestion/component/pdf_vision_dispatch.go
Model configuration, IDs, and types resolve through tenant model IDs or provider references, with active/type/access checks and expanded composite-name parsing.

Chat tenant model IDs

Layer / File(s) Summary
Chat creation and updates
internal/service/chat.go, internal/service/chat_rest_update_test.go
Chat create and REST update flows resolve and persist tenant-scoped LLM and rerank IDs, with tenant model records added to test setup.

Dataset and runtime consumers

Layer / File(s) Summary
Centralized resolution adoption
internal/service/chat_pipeline.go, internal/service/chunk/*, internal/service/dataset.go, internal/service/generator.go, internal/service/memory.go, internal/service/memory_message_service.go
Chat, retrieval, dataset, generator, and memory paths use ResolveModelConfig; dataset create/update also persists tenant embedding IDs.
Embedding and default-model tests
internal/service/dataset_update_test.go, internal/service/tenant_test.go, internal/service/model_service_test.go
Tests cover tenant embedding model IDs, updated default-model composites, tenant ID persistence, and the expanded model configuration signature.

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
Loading

Possibly related PRs

Suggested labels: 💞 feature, 🧪 test, ☯️ refactor

Suggested reviewers: xugangqiang, Lynn-Inf, yingfeng, yuzhichang, JinHai-CN

Poem

A rabbit hops through models bright,
With tenant IDs tucked snug and right.
LLMs, embeddings, defaults align,
Resolvers weave a cleaner line.
Tests thump paws: “The paths are sound!”

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title is concise and clearly reflects the main model parsing and model_id/tenant context changes.
Description check ✅ Passed The description includes the required summary context and provides detailed change breakdowns aligned with the template.

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.

@buua436 buua436 added the ci Continue Integration label Jul 10, 2026
@buua436
buua436 marked this pull request as ready for review July 10, 2026 05:13
@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label Jul 10, 2026
@buua436
buua436 marked this pull request as draft July 10, 2026 05:15
@buua436
buua436 marked this pull request as ready for review July 10, 2026 05:15
@dosubot dosubot Bot added the ☯️ refactor Pull request that refactor/refine code label Jul 10, 2026
@buua436
buua436 marked this pull request as draft July 10, 2026 05:23
@buua436
buua436 marked this pull request as ready for review July 10, 2026 05:23

@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

🧹 Nitpick comments (1)
internal/service/dataset.go (1)

3599-3611: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Dead/redundant branches in validateDatasetEmbeddingModel.

After the !strings.Contains(embeddingModel, "@") early-return, strings.Split always yields ≥2 parts, so len(parts) < 2 (Line 3609) is unreachable, and the trailing parts[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

📥 Commits

Reviewing files that changed from the base of the PR and between eca8e87 and 1fa8824.

📒 Files selected for processing (17)
  • internal/dao/tenant.go
  • internal/entity/types.go
  • internal/handler/providers.go
  • internal/ingestion/component/pdf_vision_dispatch.go
  • internal/service/chat.go
  • internal/service/chat_pipeline.go
  • internal/service/chat_rest_update_test.go
  • internal/service/chunk/chunk.go
  • internal/service/dataset.go
  • internal/service/dataset_update_test.go
  • internal/service/generator.go
  • internal/service/memory.go
  • internal/service/memory_message_service.go
  • internal/service/model_service.go
  • internal/service/model_service_test.go
  • internal/service/tenant.go
  • internal/service/tenant_test.go

Comment on lines +2481 to 2488
if embdID != "" && tenantEmbdID == "" {
resolvedID, err := NewModelProviderService().ResolveModelID(tenantID, entity.ModelTypeEmbedding, embdID)
if err == nil {
tenantEmbdID = resolvedID
} else {
return nil, common.CodeDataError, err
}
}

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.

🎯 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.go

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

Repository: 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])
PY

Repository: infiniflow/ragflow

Length of output: 1104


🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n "tenantEmbdID|embdID" internal/service/dataset.go

Repository: infiniflow/ragflow

Length of output: 1994


Align ResolveModelID handling in create and update

  • CreateDataset fails when the tenant default EmbdID can’t be resolved, but UpdateDataset ignores the same ResolveModelID error and continues with an empty tenant_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, validateDatasetEmbeddingModel has an unreachable len(parts) < 2 branch after the Contains("@") 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.

Comment on lines +2317 to +2327
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)
}

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.

🔒 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 internal

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

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

Comment on lines 788 to 793
err = s.tenantDAO.Update(ownedTenant.TenantID, map[string]interface{}{
modelTypeID: defaultModel,
modelTypeID: defaultModel,
tenantModelTypeID: tenantModelID,
})

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.

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

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration ☯️ refactor Pull request that refactor/refine code size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants