Repository navigation
Use GetChatModel, remove duplicate functions in model_service.go - #14546
Conversation
📝 WalkthroughWalkthroughThis PR removes the ChangesChatModel migration & related wiring
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ 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. Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (8)
internal/cli/user_parser.gointernal/entity/types.gointernal/handler/providers.gointernal/service/chunk.gointernal/service/generator.gointernal/service/metadata_filter.gointernal/service/model_service.gointernal/service/tenant.go
💤 Files with no reviewable changes (3)
- internal/entity/types.go
- internal/handler/providers.go
- internal/cli/user_parser.go
| 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)) |
There was a problem hiding this comment.
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.
| case entity.ModelTypeTTS: | ||
| modelID = *tenant.TTSID |
There was a problem hiding this comment.
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.
| 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 Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
🧹 Nitpick comments (2)
internal/service/chunk.go (1)
273-287: ⚡ Quick winUse
entity.ModelTypeChatinstead of the bare"chat"literal.Line 275 passes the string literal
"chat"totenantSvc.GetDefaultModelName(...), while the structurally identical call at line 233 (a few lines above) usesentity.ModelTypeChat.GetDefaultModelNameis typed as(tenantID string, modelType entity.ModelType), so the literal works only via implicit conversion of the untyped string constant — and silently breaks the momentModelTypeChat'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 valueDrop redundant
TrimPrefixcalls and hoist regexes to package scope.
- Lines 161-162 are subsumed by the case-insensitive regex on line 163 (which already handles both
Output:andoutput: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
CrossLanguagesinvocation; compile them once at package scope, mirroring the existingthinkBlockREpattern 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
📒 Files selected for processing (4)
internal/cli/user_parser.gointernal/service/chunk.gointernal/service/generator.gointernal/service/metadata_filter.go
💤 Files with no reviewable changes (1)
- internal/cli/user_parser.go
What problem does this PR solve?
Use GetChatModel, remove duplicate functions in model_service.go
Type of change