Skip to content

Use GetChatModel, remove duplicate functions in model_service.go - #14546

Merged
JinHai-CN merged 2 commits into
infiniflow:mainfrom
qinling0210:refactor_GetChatModel
May 6, 2026
Merged

JinHai-CN merged 2 commits into
infiniflow:mainfrom
qinling0210:refactor_GetChatModel

Conversation

@qinling0210

@qinling0210 qinling0210 commented Apr 30, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Use GetChatModel, remove duplicate functions in model_service.go

Type of change

  • Refactoring

@qinling0210 qinling0210 self-assigned this Apr 30, 2026
@coderabbitai

coderabbitai Bot commented Apr 30, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This PR removes the ModelCredentials type and migrates metadata, generation, and retrieval flows to use *modelModule.ChatModel; updates model resolution to return "default" for legacy names; relaxes instance-name validation to accept "default"; and adds tenant default model lookup.

Changes

ChatModel migration & related wiring

Layer / File(s) Summary
Data Shape / Types
internal/entity/types.go
Removed ModelCredentials type.
Core Implementation
internal/service/generator.go, internal/service/metadata_filter.go
Replaced creds *entity.ModelCredentials parameters with chatModel *modelModule.ChatModel in KeywordExtraction, CrossLanguages, GenMetaFilter; use chatModel.ModelDriver.ChatWithMessages and add nil/response checks.
Retrieval & Filtering Integration
internal/service/chunk.go
Resolve chatModelForFilter from search_config.chat_id or tenant default; pass chatModelForFilter into ApplyMetaDataFilter; lazy-load tenant chat model for cross-language/keyword extraction.
Model provider / tenant wiring
internal/service/model_service.go, internal/service/tenant.go
Removed API-key and credential helper methods (ChatWithMessagesToModelByApiKey, GetDefaultModel, GetModelByName); added TenantService.GetDefaultModelName; parseModelName now sets legacy composite names to instance "default".
CLI / Handler
internal/cli/user_parser.go, internal/handler/providers.go
Removed guard rejecting instance_name == "default" so parser and handler forward "default" instance names.
Tests / Docs (no changes in this diff)
-
No test or documentation files updated in this diff.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Client
  participant Handler
  participant ChunkService
  participant TenantService
  participant ChatModel as ChatModel/ModelDriver

  Client->>Handler: Create/Query with instance_name ("default" allowed)
  Handler->>ChunkService: RetrievalTest / ApplyMetaDataFilter request
  ChunkService->>TenantService: GetDefaultModelName (if needed)
  TenantService-->>ChunkService: model name / chat_id
  ChunkService->>ChatModel: ChatWithMessages (via chatModel.ModelDriver)
  ChatModel-->>ChunkService: response.Answer
  ChunkService->>Handler: filtered/translated results
  Handler-->>Client: response
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

☯️ refactor

Poem

🐰 Hopping through code with a curious twitch,
I swapped credentials for a ChatModel switch.
"default" can stay, no longer denied—
Tenants find models with a gentler guide.
Refactor done; the rabbit's pleased and rich.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main changes: replacing logic with GetChatModel and removing duplicate functions in model_service.go, which are confirmed by the raw summary.
Description check ✅ Passed The description is minimal but complete according to the template, identifying this as a refactoring change. However, it lacks detail about the specific problem being solved beyond mentioning the changes themselves.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
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.

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


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 and usage tips.

@qinling0210 qinling0210 added the ci Continue Integration label Apr 30, 2026
@qinling0210
qinling0210 marked this pull request as ready for review April 30, 2026 12:37
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Apr 30, 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: 2

🤖 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/service/chunk.go`:
- Around line 219-243: The metadata/filter/chat-paths call
modelProviderSvc.GetChatModel(...) but that helper only returns the shared
provider driver and does not apply tenant-local routing (base_url / NewInstance
/ ModelClass) used in the chat path; update these call sites (the GetChatModel
calls around chatModelForFilter and the similar block at lines ~273-287) to use
the same tenant-local routing logic found in internal/service/model_service.go
(the base_url / NewInstance / ModelClass handling in the chat model retrieval
block) — either by invoking the same helper used by the active chat path or by
extending ModelProviderService.GetChatModel to return a tenant-local instance
when the model config indicates a local/base_url deployment so metadata
filtering, translation and keyword extraction use the correct tenant-local
endpoint.

In `@internal/service/tenant.go`:
- Around line 329-330: In the switch branch handling entity.ModelTypeTTS, avoid
unguarded dereference of tenant.TTSID; check if tenant.TTSID != nil before
assigning modelID = *tenant.TTSID and otherwise leave modelID as an empty string
(or explicitly set modelID = "") so the helper continues to return an empty
string when no default TTS is configured; update the ModelTypeTTS case in the
same helper (where modelID is assigned) to perform this nil check on
tenant.TTSID.
🪄 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: 8fe324da-812f-439e-86bf-696efcf46a4f

📥 Commits

Reviewing files that changed from the base of the PR and between d38d6e7 and 2e55297.

📒 Files selected for processing (8)
  • internal/cli/user_parser.go
  • internal/entity/types.go
  • internal/handler/providers.go
  • internal/service/chunk.go
  • internal/service/generator.go
  • internal/service/metadata_filter.go
  • internal/service/model_service.go
  • internal/service/tenant.go
💤 Files with no reviewable changes (3)
  • internal/entity/types.go
  • internal/handler/providers.go
  • internal/cli/user_parser.go

Comment thread internal/service/chunk.go
Comment on lines 219 to +243
if chatID != "" {
// Use chat_id from search_config
creds, err = modelProviderSvc.GetModelByName(chatID, tenantIDs[0])
// Use chat_id from search_config (it's actually the model name)
chatModelForFilter, err = modelProviderSvc.GetChatModel(tenantIDs[0], chatID)
if err != nil {
logger.Warn("Failed to get chat model from search_config chat_id, using tenant default", zap.String("chatID", chatID), zap.Error(err))
} else {
logger.Info("Fetched chat model (from search_config) for metadata filter",
zap.String("chatID", chatID),
zap.String("tenantID", tenantIDs[0]),
zap.String("providerName", creds.ProviderName),
zap.String("modelName", creds.ModelName))
zap.String("tenantID", tenantIDs[0]))
}
}
// If no chatID from search_config, or creds not found, use tenant default
if creds == nil {
creds, err = modelProviderSvc.GetDefaultModel(entity.ModelTypeChat, tenantIDs[0])
if err != nil {
logger.Warn("Failed to get tenant default chat model for meta_data_filter", zap.Error(err))
// If no chatID from search_config, or chatModel not found, use tenant default
if chatModelForFilter == nil {
tenantSvc := NewTenantService()
modelName, err := tenantSvc.GetDefaultModelName(tenantIDs[0], entity.ModelTypeChat)
if err != nil || modelName == "" {
logger.Warn("Failed to get tenant default chat model name for meta_data_filter", zap.Error(err))
} else {
logger.Info("Fetched chat model (tenant default) for metadata filter",
zap.String("tenantID", tenantIDs[0]),
zap.String("providerName", creds.ProviderName),
zap.String("modelName", creds.ModelName))
chatModelForFilter, err = modelProviderSvc.GetChatModel(tenantIDs[0], modelName)
if err != nil {
logger.Warn("Failed to get chat model for meta_data_filter", zap.Error(err))
} else {
logger.Info("Fetched chat model (tenant default) for metadata filter",
zap.String("tenantID", tenantIDs[0]),
zap.String("modelName", 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 | 🟠 Major | 🏗️ Heavy lift

These new GetChatModel call sites drop tenant-local instance routing.

Both paths now rely on ModelProviderService.GetChatModel(), but that helper currently just wraps getModelConfig() and returns the shared provider driver. It does not apply the base_url / NewInstance(...) / ModelClass handling that the existing chat path still uses for active local deployments in internal/service/model_service.go:754-787. After this refactor, metadata filtering, translation, and keyword extraction can hit the wrong endpoint for locally deployed models.

Also applies to: 273-287

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/service/chunk.go` around lines 219 - 243, The
metadata/filter/chat-paths call modelProviderSvc.GetChatModel(...) but that
helper only returns the shared provider driver and does not apply tenant-local
routing (base_url / NewInstance / ModelClass) used in the chat path; update
these call sites (the GetChatModel calls around chatModelForFilter and the
similar block at lines ~273-287) to use the same tenant-local routing logic
found in internal/service/model_service.go (the base_url / NewInstance /
ModelClass handling in the chat model retrieval block) — either by invoking the
same helper used by the active chat path or by extending
ModelProviderService.GetChatModel to return a tenant-local instance when the
model config indicates a local/base_url deployment so metadata filtering,
translation and keyword extraction use the correct tenant-local endpoint.

Comment on lines +329 to +330
case entity.ModelTypeTTS:
modelID = *tenant.TTSID

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 | ⚡ Quick win

Guard the optional TTS default before dereferencing it.

Tenant.TTSID is nullable, so *tenant.TTSID will panic for tenants that have no default TTS model configured. That also contradicts this helper's documented behavior of returning an empty string when no default is set.

Suggested fix
 	case entity.ModelTypeTTS:
-		modelID = *tenant.TTSID
+		if tenant.TTSID == nil {
+			return "", nil
+		}
+		modelID = *tenant.TTSID
📝 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
case entity.ModelTypeTTS:
modelID = *tenant.TTSID
case entity.ModelTypeTTS:
if tenant.TTSID == nil {
return "", nil
}
modelID = *tenant.TTSID
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/service/tenant.go` around lines 329 - 330, In the switch branch
handling entity.ModelTypeTTS, avoid unguarded dereference of tenant.TTSID; check
if tenant.TTSID != nil before assigning modelID = *tenant.TTSID and otherwise
leave modelID as an empty string (or explicitly set modelID = "") so the helper
continues to return an empty string when no default TTS is configured; update
the ModelTypeTTS case in the same helper (where modelID is assigned) to perform
this nil check on tenant.TTSID.

@codecov

codecov Bot commented Apr 30, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (aa57b5b) to head (7c83ff4).

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14546   +/-   ##
=======================================
  Coverage   94.16%   94.16%           
=======================================
  Files          10       10           
  Lines         703      703           
  Branches      112      112           
=======================================
  Hits          662      662           
  Misses         25       25           
  Partials       16       16           

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

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

🧹 Nitpick comments (2)
internal/service/chunk.go (1)

273-287: ⚡ Quick win

Use entity.ModelTypeChat instead of the bare "chat" literal.

Line 275 passes the string literal "chat" to tenantSvc.GetDefaultModelName(...), while the structurally identical call at line 233 (a few lines above) uses entity.ModelTypeChat. GetDefaultModelName is typed as (tenantID string, modelType entity.ModelType), so the literal works only via implicit conversion of the untyped string constant — and silently breaks the moment ModelTypeChat's underlying value diverges from "chat". Keep the two call sites consistent and tied to the constant.

♻️ Proposed fix
-		modelName, err := tenantSvc.GetDefaultModelName(tenantIDs[0], "chat")
+		modelName, err := tenantSvc.GetDefaultModelName(tenantIDs[0], entity.ModelTypeChat)
🤖 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/chunk.go` around lines 273 - 287, Replace the hardcoded
"chat" string with the canonical constant: call
tenantSvc.GetDefaultModelName(tenantIDs[0], entity.ModelTypeChat) instead of
using the literal; update the call in the block that obtains modelName (the one
that then uses modelProviderSvc.GetChatModel and assigns chatModel) so it uses
entity.ModelTypeChat to match the other call site and the GetDefaultModelName
signature.
internal/service/generator.go (1)

161-167: 💤 Low value

Drop redundant TrimPrefix calls and hoist regexes to package scope.

  • Lines 161-162 are subsumed by the case-insensitive regex on line 163 (which already handles both Output: and output: plus optional whitespace). Removing them avoids subtle inconsistencies (the prefix calls don't strip trailing whitespace, the regex does).
  • The regexes on lines 163-164 are recompiled on every CrossLanguages invocation; compile them once at package scope, mirroring the existing thinkBlockRE pattern used at line 153.
♻️ Proposed refactor

At package scope (near thinkBlockRE):

var (
    crossLangOutputRE  = regexp.MustCompile(`(?i)^output:\s*`)
    crossLangNewlineRE = regexp.MustCompile(`\n+`)
)

Then in CrossLanguages:

-	// Parse response
-	result = strings.TrimPrefix(result, "Output:")
-	result = strings.TrimPrefix(result, "output:")
-	result = regexp.MustCompile(`(?i)^output:\s*`).ReplaceAllString(result, "")
-	result = regexp.MustCompile(`\n+`).ReplaceAllString(result, "")
-	result = strings.TrimSpace(result)
+	// Parse response
+	result = crossLangOutputRE.ReplaceAllString(result, "")
+	result = crossLangNewlineRE.ReplaceAllString(result, "")
+	result = strings.TrimSpace(result)
🤖 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/generator.go` around lines 161 - 167, In CrossLanguages,
remove the redundant strings.TrimPrefix calls around "Output:"/"output:" and
replace the inline regexp.MustCompile calls with package-level compiled regex
variables (e.g., define var crossLangOutputRE =
regexp.MustCompile(`(?i)^output:\s*`) and var crossLangNewlineRE =
regexp.MustCompile(`\n+`) alongside thinkBlockRE), then update CrossLanguages to
use crossLangOutputRE.ReplaceAllString and crossLangNewlineRE.ReplaceAllString
so the regexes are compiled once and the logic remains case-insensitive and
trims whitespace/newlines consistently.
🤖 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.

Nitpick comments:
In `@internal/service/chunk.go`:
- Around line 273-287: Replace the hardcoded "chat" string with the canonical
constant: call tenantSvc.GetDefaultModelName(tenantIDs[0], entity.ModelTypeChat)
instead of using the literal; update the call in the block that obtains
modelName (the one that then uses modelProviderSvc.GetChatModel and assigns
chatModel) so it uses entity.ModelTypeChat to match the other call site and the
GetDefaultModelName signature.

In `@internal/service/generator.go`:
- Around line 161-167: In CrossLanguages, remove the redundant
strings.TrimPrefix calls around "Output:"/"output:" and replace the inline
regexp.MustCompile calls with package-level compiled regex variables (e.g.,
define var crossLangOutputRE = regexp.MustCompile(`(?i)^output:\s*`) and var
crossLangNewlineRE = regexp.MustCompile(`\n+`) alongside thinkBlockRE), then
update CrossLanguages to use crossLangOutputRE.ReplaceAllString and
crossLangNewlineRE.ReplaceAllString so the regexes are compiled once and the
logic remains case-insensitive and trims whitespace/newlines consistently.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 5e602c93-55dc-4f60-9d0d-ceb5244ee27b

📥 Commits

Reviewing files that changed from the base of the PR and between 2e55297 and 7c83ff4.

📒 Files selected for processing (4)
  • internal/cli/user_parser.go
  • internal/service/chunk.go
  • internal/service/generator.go
  • internal/service/metadata_filter.go
💤 Files with no reviewable changes (1)
  • internal/cli/user_parser.go

@JinHai-CN
JinHai-CN merged commit 7335916 into infiniflow:main May 6, 2026
1 check passed
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.

2 participants