Repository navigation
Add extra field to model instance - #14203
Conversation
Signed-off-by: Jin Hai <[email protected]>
📝 WalkthroughWalkthroughProvider configurations and model interfaces were changed to support region-keyed URLs (map of regions), model type renames (e.g., Changes
Sequence Diagram(s)sequenceDiagram
participant H as HTTP Handler
participant S as ModelService
participant D as DAO (TenantModelInstance)
participant MD as ModelDriver
H->>S: ChatToModel(provider, instance, model, user, message, chatConfig)
S->>D: Load instance.Extra
D-->>S: Extra JSON (e.g., {"region":"<r>"})
S->>S: Set chatConfig.Region = region (or "default")
S->>MD: Chat(modelName, apiKey, message, chatConfig)
MD->>MD: region := chatConfig.Region or "default"
MD->>MD: baseURL := BaseURL[region]
MD->>MD: make request to baseURL
MD-->>S: response
S-->>H: return result
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 1 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (1 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Warning Review ran into problems🔥 ProblemsTimed out fetching pipeline failures after 30000ms Comment |
There was a problem hiding this comment.
Actionable comments posted: 7
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
internal/entity/models/factory.go (1)
33-39:⚠️ Potential issue | 🟠 MajorFail fast for unsupported providers instead of returning
DummyModel.With
conf/models/openai.jsonandconf/models/xai.jsonupdated in this PR, those providers will now load and look healthy, but this factory still routes every non-zhipu-aiprovider to a driver that only returnsnot implemented. That defers the failure to the first user request.Suggested fix
import ( + "fmt" "strings" ) @@ switch providerLower { case "zhipu-ai": return NewZhipuAIModel(baseURL, urlSuffix), nil default: - return NewDummyModel(baseURL, urlSuffix), nil + return nil, fmt.Errorf("model driver for provider %q is not implemented", providerName) } }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/entity/models/factory.go` around lines 33 - 39, The factory function ModelFactory.CreateModelDriver currently maps any non-"zhipu-ai" provider to NewDummyModel which defers errors to runtime; change it to fail fast by returning a clear error for unsupported providers instead of NewDummyModel. Update CreateModelDriver to check providerLower and return (nil, fmt.Errorf("unsupported model provider: %s", providerName)) for unknown providers (referencing ModelFactory.CreateModelDriver, NewDummyModel, ModelDriver), ensuring callers receive an immediate error when a provider has no real driver.internal/entity/models/zhipu-ai.go (1)
56-85:⚠️ Potential issue | 🔴 CriticalFix the non-stream chat URL selection.
BaseURLis amap[string]string, but theChatmethod still formats the entire map with%sand never readschatModelConfig.Region. This produces a malformed URL like "map[...]". The streaming (ChatStreamlyWithSender) and embedding (EncodeToEmbedding) paths handle region routing correctly; only the non-streamChatneeds fixing.🛠 Proposed fix
func (z *ZhipuAIModel) Chat(modelName, apiKey, message *string, chatModelConfig *ChatConfig) (string, error) { if message == nil { return "", fmt.Errorf("message is nil") } - url := fmt.Sprintf("%s/%s", z.BaseURL, z.URLSuffix.Chat) + region := "default" + if chatModelConfig != nil && chatModelConfig.Region != nil && *chatModelConfig.Region != "" { + region = *chatModelConfig.Region + } + baseURL, ok := z.BaseURL[region] + if !ok || baseURL == "" { + return "", fmt.Errorf("base URL not configured for region %q", region) + } + + url := fmt.Sprintf("%s/%s", baseURL, z.URLSuffix.Chat)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/entity/models/zhipu-ai.go` around lines 56 - 85, The Chat method builds the request URL incorrectly by formatting z.BaseURL (a map[string]string) with %s; update ZhipuAIModel.Chat to pick the correct base URL string before building the URL: read region from chatModelConfig.Region (or use a sensible fallback if nil), look up the base string in z.BaseURL (e.g., base := z.BaseURL[*chatModelConfig.Region] or fallback to a default key or the first map value), then form url := fmt.Sprintf("%s/%s", base, z.URLSuffix.Chat). Ensure the code checks for missing map entries and uses the same region-resolution logic as ChatStreamlyWithSender and EncodeToEmbedding.
🤖 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/entity/model.go`:
- Around line 148-152: The URL field on Model providers was changed to
map[string]string but callers (GetModelUrl, ListProviders, GetProviderByName)
still treat it as a single string; update code to resolve a concrete string
before reuse by (1) adding a helper to pick a region key (e.g., "default" or a
provided region param) from provider.URL map and return providerURL string, (2)
use that helper inside GetModelUrl to concatenate suffixes instead of formatting
the map directly, and (3) normalize the payloads returned by ListProviders and
GetProviderByName to expose the resolved string URL (or include an explicit
region field) so callers receive a stable non-breaking string value.
In `@internal/entity/models/types.go`:
- Line 6: The non-stream Chat implementation in
internal/entity/models/zhipu-ai.go must be updated to use the new *ChatConfig
parameter: stop treating BaseURL as a formatted string and instead read
modelConfig.Region to select the proper base URL (e.g., BaseURL[region]) as done
in streaming/embedding paths; ensure you handle nil modelConfig or missing/empty
Region with a sensible default or error, and update the function signature and
URL construction in the Chat method to build a valid URL from the selected
BaseURL rather than using fmt.Sprintf on a map.
In `@internal/entity/models/zhipu-ai.go`:
- Around line 145-152: Both ChatStreamlyWithSender and EncodeToEmbedding
currently assume chatModelConfig is non-nil and that z.BaseURL contains the
chosen region; guard both. In each function (ZhipuAIModel.ChatStreamlyWithSender
and ZhipuAIModel.EncodeToEmbedding) first check if chatModelConfig is nil, then
if chatModelConfig.Region is nil use a default region string; next perform a
safe map lookup like urlBase, ok := z.BaseURL[region] and return an error if !ok
or urlBase == "" instead of using an empty string; finally build the request URL
from urlBase (e.g. urlBase + "/chat/completions" or the embedding path) so you
never format a malformed URL or panic on nil config.
In `@internal/entity/tenant_model_instance.go`:
- Line 26: The Extra struct field currently uses an invalid JSON default
('active'); update the GORM tag on the Extra field in the TenantModelInstance
struct so the default is valid JSON (e.g., default:'{}') instead of 'active',
and ensure any schema/migration that creates/updates this column uses the same
JSON-safe default so rows created without an explicit Extra value parse
correctly.
In `@internal/handler/providers.go`:
- Line 277: The handler currently hardcodes the region string "default" when
calling h.modelProviderService.CreateProviderInstance(providerName,
req.InstanceName, req.APIKey, userID, "default"); change this to accept a region
from the create-instance request (e.g., add a Region or RegionName field to the
request struct/parsing code), pass that value into CreateProviderInstance
instead of the hardcoded "default" (e.g.,
h.modelProviderService.CreateProviderInstance(providerName, req.InstanceName,
req.APIKey, userID, req.Region)), and fall back to "default" only when
req.Region is empty; also update any request validation and the
CreateProviderInstance signature/usage if necessary to ensure the region is
propagated to provider initialization.
In `@internal/service/model_service.go`:
- Around line 577-578: The code sets modelConfig.Region unconditionally from
extra["region"], which overrides driver defaults when the value is empty; change
the assignment in the non-streaming path (where it does region :=
extra["region"]; modelConfig.Region = ®ion) to only set modelConfig.Region
when region != "" (leave it nil otherwise), and apply the same conditional check
in the streaming path where modelConfig.Region is set (the later occurrence
around the streaming-related block) so both paths preserve the default region
when Extra.region is blank.
- Around line 315-320: The code unmarshals instance.Extra with json.Unmarshal
which returns EOF for empty strings; update the parsing so blank Extra is
treated as an empty object instead of failing: check if instance.Extra is empty
or only whitespace and set extra = map[string]string{} (or use json.Unmarshal on
"{}") before calling json.Unmarshal, and only return an error when
instance.Extra is non-empty and invalid JSON; apply the same pattern to the
other json.Unmarshal sites in this file that parse Extra (the other occurrences
around the instance handling logic).
---
Outside diff comments:
In `@internal/entity/models/factory.go`:
- Around line 33-39: The factory function ModelFactory.CreateModelDriver
currently maps any non-"zhipu-ai" provider to NewDummyModel which defers errors
to runtime; change it to fail fast by returning a clear error for unsupported
providers instead of NewDummyModel. Update CreateModelDriver to check
providerLower and return (nil, fmt.Errorf("unsupported model provider: %s",
providerName)) for unknown providers (referencing
ModelFactory.CreateModelDriver, NewDummyModel, ModelDriver), ensuring callers
receive an immediate error when a provider has no real driver.
In `@internal/entity/models/zhipu-ai.go`:
- Around line 56-85: The Chat method builds the request URL incorrectly by
formatting z.BaseURL (a map[string]string) with %s; update ZhipuAIModel.Chat to
pick the correct base URL string before building the URL: read region from
chatModelConfig.Region (or use a sensible fallback if nil), look up the base
string in z.BaseURL (e.g., base := z.BaseURL[*chatModelConfig.Region] or
fallback to a default key or the first map value), then form url :=
fmt.Sprintf("%s/%s", base, z.URLSuffix.Chat). Ensure the code checks for missing
map entries and uses the same region-resolution logic as ChatStreamlyWithSender
and EncodeToEmbedding.
🪄 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: c55be68c-10a4-4414-af63-b9487e31eab4
📒 Files selected for processing (11)
conf/models/openai.jsonconf/models/xai.jsonconf/models/zhipu-ai.jsoninternal/entity/model.gointernal/entity/models/dummy.gointernal/entity/models/factory.gointernal/entity/models/types.gointernal/entity/models/zhipu-ai.gointernal/entity/tenant_model_instance.gointernal/handler/providers.gointernal/service/model_service.go
| Name string `json:"name"` | ||
| Tags []string `json:"tags"` | ||
| URL map[string]string `json:"url"` | ||
| URLSuffix models.URLSuffix `json:"url_suffix"` | ||
| Models []*Model `json:"models"` |
There was a problem hiding this comment.
Resolve the URL map before reusing it as a string.
After this type change, GetModelUrl still concatenates provider.URL with suffixes at Lines 326-336 using %s, so callers will get malformed endpoints instead of usable URLs. The same change also alters the payload shape returned by ListProviders and GetProviderByName. If this feature is meant to stay non-breaking, normalize to "default" or an explicit region before exposing/reusing the value.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/model.go` around lines 148 - 152, The URL field on Model
providers was changed to map[string]string but callers (GetModelUrl,
ListProviders, GetProviderByName) still treat it as a single string; update code
to resolve a concrete string before reuse by (1) adding a helper to pick a
region key (e.g., "default" or a provided region param) from provider.URL map
and return providerURL string, (2) use that helper inside GetModelUrl to
concatenate suffixes instead of formatting the map directly, and (3) normalize
the payloads returned by ListProviders and GetProviderByName to expose the
resolved string URL (or include an explicit region field) so callers receive a
stable non-breaking string value.
| ChatStreamly(modelName, apiKey, message *string, genConf map[string]interface{}) (<-chan string, error) | ||
| // ChatStreamlyWithChannel sends a message and streams response to channel (better performance) | ||
| ChatStreamlyWithChannel(modelName, apiKey, message *string, genConf map[string]interface{}, resultChan chan<- string) error | ||
| Chat(modelName, apiKey, message *string, modelConfig *ChatConfig) (string, error) |
There was a problem hiding this comment.
Update the non-stream Chat implementation too.
Chat now takes *ChatConfig, but the current internal/entity/models/zhipu-ai.go Chat implementation still formats BaseURL as a string and never reads modelConfig.Region. Streaming and embedding already use BaseURL[region], so the regular chat path will still ignore region and build a malformed URL once BaseURL is a map.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/models/types.go` at line 6, The non-stream Chat
implementation in internal/entity/models/zhipu-ai.go must be updated to use the
new *ChatConfig parameter: stop treating BaseURL as a formatted string and
instead read modelConfig.Region to select the proper base URL (e.g.,
BaseURL[region]) as done in streaming/embedding paths; ensure you handle nil
modelConfig or missing/empty Region with a sensible default or error, and update
the function signature and URL construction in the Chat method to build a valid
URL from the selected BaseURL rather than using fmt.Sprintf on a map.
| func (z *ZhipuAIModel) ChatStreamlyWithSender(modelName, apiKey, message *string, chatModelConfig *ChatConfig, sender func(*string, *string) error) error { | ||
| var region = "default" | ||
| if chatModelConfig.Region != nil { | ||
| region = *chatModelConfig.Region | ||
| } | ||
|
|
||
| // Send [DONE] marker for OpenAI compatibility | ||
| resultChan <- "[DONE]" | ||
|
|
||
| return scanner.Err() | ||
| } | ||
|
|
||
| // ChatStreamlyWithSender sends a message and streams response via sender function (best performance, no channel) | ||
| func (z *ZhipuAIModel) ChatStreamlyWithSender(modelName, apiKey, message *string, modelConfig *ChatConfig, sender func(*string, *string) error) error { | ||
| url := fmt.Sprintf("%s/chat/completions", z.BaseURL) | ||
| url := fmt.Sprintf("%s/chat/completions", z.BaseURL[region]) | ||
|
|
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -e
sed -n '145,170p' internal/entity/models/zhipu-ai.go
sed -n '295,305p' internal/entity/models/zhipu-ai.goRepository: infiniflow/ragflow
Length of output: 1201
Guard config reads and validate the region lookup.
Both ChatStreamlyWithSender and EncodeToEmbedding methods dereference the config's Region field without first checking if the config pointer is nil, and they perform unchecked map lookups on z.BaseURL[region]. When a region key doesn't exist in the map, Go returns an empty string, resulting in a malformed URL. If the config is nil, the code panics.
🛠 Proposed fixes
For ChatStreamlyWithSender (lines 145-152):
- var region = "default"
- if chatModelConfig.Region != nil {
- region = *chatModelConfig.Region
- }
-
- url := fmt.Sprintf("%s/chat/completions", z.BaseURL[region])
+ region := "default"
+ if chatModelConfig != nil && chatModelConfig.Region != nil && *chatModelConfig.Region != "" {
+ region = *chatModelConfig.Region
+ }
+ baseURL, ok := z.BaseURL[region]
+ if !ok || baseURL == "" {
+ return fmt.Errorf("base URL not configured for region %q", region)
+ }
+
+ url := fmt.Sprintf("%s/chat/completions", baseURL)For EncodeToEmbedding (lines 295-302):
- var region = "default"
- if embeddingConfig.Region != nil {
- region = *embeddingConfig.Region
- }
-
- url := fmt.Sprintf("%s/embedding", z.BaseURL[region])
+ region := "default"
+ if embeddingConfig != nil && embeddingConfig.Region != nil && *embeddingConfig.Region != "" {
+ region = *embeddingConfig.Region
+ }
+ baseURL, ok := z.BaseURL[region]
+ if !ok || baseURL == "" {
+ return nil, fmt.Errorf("base URL not configured for region %q", region)
+ }
+
+ url := fmt.Sprintf("%s/embedding", baseURL)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/models/zhipu-ai.go` around lines 145 - 152, Both
ChatStreamlyWithSender and EncodeToEmbedding currently assume chatModelConfig is
non-nil and that z.BaseURL contains the chosen region; guard both. In each
function (ZhipuAIModel.ChatStreamlyWithSender and
ZhipuAIModel.EncodeToEmbedding) first check if chatModelConfig is nil, then if
chatModelConfig.Region is nil use a default region string; next perform a safe
map lookup like urlBase, ok := z.BaseURL[region] and return an error if !ok or
urlBase == "" instead of using an empty string; finally build the request URL
from urlBase (e.g. urlBase + "/chat/completions" or the embedding path) so you
never format a malformed URL or panic on nil config.
| ProviderID string `gorm:"column:provider_id;size:32;not null;uniqueIndex:idx_api_key_provider_id" json:"provider_id"` | ||
| APIKey string `gorm:"column:api_key;size:512;not null;uniqueIndex:idx_api_key_provider_id" json:"api_key"` | ||
| Status string `gorm:"column:status;size:32;default:'active'" json:"status"` | ||
| Extra string `gorm:"column:extra;size:512;default:'active'" json:"extra"` |
There was a problem hiding this comment.
Use a JSON-safe default for Extra.
model_service now treats this column as JSON for region metadata. A default of 'active' is invalid JSON, so rows created without an explicit Extra value will fail on the read path.
Suggested fix
- Extra string `gorm:"column:extra;size:512;default:'active'" json:"extra"`
+ Extra string `gorm:"column:extra;size:512;default:'{}'" json:"extra"`📝 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.
| Extra string `gorm:"column:extra;size:512;default:'active'" json:"extra"` | |
| Extra string `gorm:"column:extra;size:512;default:'{}'" json:"extra"` |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/tenant_model_instance.go` at line 26, The Extra struct field
currently uses an invalid JSON default ('active'); update the GORM tag on the
Extra field in the TenantModelInstance struct so the default is valid JSON
(e.g., default:'{}') instead of 'active', and ensure any schema/migration that
creates/updates this column uses the same JSON-safe default so rows created
without an explicit Extra value parse correctly.
| userID := c.GetString("user_id") | ||
|
|
||
| _, err := h.modelProviderService.CreateProviderInstance(providerName, req.InstanceName, req.APIKey, userID) | ||
| _, err := h.modelProviderService.CreateProviderInstance(providerName, req.InstanceName, req.APIKey, userID, "default") |
There was a problem hiding this comment.
Expose region in the create-instance API.
Hardcoding "default" here means clients cannot actually choose a region-specific base URL when creating an instance, so the new feature is unreachable through this handler.
Suggested fix
type CreateProviderInstanceRequest struct {
InstanceName string `json:"instance_name" binding:"required"`
APIKey string `json:"api_key" binding:"required"`
+ Region string `json:"region"`
}
@@
- _, err := h.modelProviderService.CreateProviderInstance(providerName, req.InstanceName, req.APIKey, userID, "default")
+ region := req.Region
+ if region == "" {
+ region = "default"
+ }
+
+ _, err := h.modelProviderService.CreateProviderInstance(providerName, req.InstanceName, req.APIKey, userID, region)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/handler/providers.go` at line 277, The handler currently hardcodes
the region string "default" when calling
h.modelProviderService.CreateProviderInstance(providerName, req.InstanceName,
req.APIKey, userID, "default"); change this to accept a region from the
create-instance request (e.g., add a Region or RegionName field to the request
struct/parsing code), pass that value into CreateProviderInstance instead of the
hardcoded "default" (e.g.,
h.modelProviderService.CreateProviderInstance(providerName, req.InstanceName,
req.APIKey, userID, req.Region)), and fall back to "default" only when
req.Region is empty; also update any request validation and the
CreateProviderInstance signature/usage if necessary to ensure the region is
propagated to provider initialization.
| // convert instance.Extra (json string) to map | ||
| var extra map[string]string | ||
| err = json.Unmarshal([]byte(instance.Extra), &extra) | ||
| if err != nil { | ||
| return nil, common.CodeServerError, err | ||
| } |
There was a problem hiding this comment.
Keep Extra parsing backward-compatible.
json.Unmarshal([]byte(instance.Extra), ...) returns EOF for legacy rows where Extra is empty, so existing instances will start failing to list/show/chat after this rollout. Treat blank Extra as {} and only reject non-empty malformed JSON.
🛠 Proposed fix
- var extra map[string]string
- err = json.Unmarshal([]byte(instance.Extra), &extra)
- if err != nil {
- return nil, common.CodeServerError, err
- }
+ extra := map[string]string{}
+ if strings.TrimSpace(instance.Extra) != "" {
+ err = json.Unmarshal([]byte(instance.Extra), &extra)
+ if err != nil {
+ return nil, common.CodeServerError, err
+ }
+ }Apply the same guard at the other new json.Unmarshal sites in this file.
Also applies to: 360-365, 571-575, 629-633
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/service/model_service.go` around lines 315 - 320, The code
unmarshals instance.Extra with json.Unmarshal which returns EOF for empty
strings; update the parsing so blank Extra is treated as an empty object instead
of failing: check if instance.Extra is empty or only whitespace and set extra =
map[string]string{} (or use json.Unmarshal on "{}") before calling
json.Unmarshal, and only return an error when instance.Extra is non-empty and
invalid JSON; apply the same pattern to the other json.Unmarshal sites in this
file that parse Extra (the other occurrences around the instance handling
logic).
| region := extra["region"] | ||
| modelConfig.Region = ®ion |
There was a problem hiding this comment.
Preserve the default region when Extra.region is blank.
If region is missing or empty, assigning ®ion forces downstream drivers to use BaseURL[""] instead of their "default" fallback. Only override modelConfig.Region when the stored value is non-empty.
🛠 Proposed fix
- region := extra["region"]
- modelConfig.Region = ®ion
+ if region := strings.TrimSpace(extra["region"]); region != "" {
+ modelConfig.Region = ®ion
+ }Apply the same change in the streaming path as well.
Also applies to: 635-636
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/service/model_service.go` around lines 577 - 578, The code sets
modelConfig.Region unconditionally from extra["region"], which overrides driver
defaults when the value is empty; change the assignment in the non-streaming
path (where it does region := extra["region"]; modelConfig.Region = ®ion) to
only set modelConfig.Region when region != "" (leave it nil otherwise), and
apply the same conditional check in the streaming path where modelConfig.Region
is set (the later occurrence around the streaming-related block) so both paths
preserve the default region when Extra.region is blank.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14203 +/- ##
=======================================
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. 🚀 New features to boost your workflow:
|
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (4)
internal/cli/lexer.go (1)
181-341:⚠️ Potential issue | 🟠 MajorKeep the old model-type keywords as aliases.
Dropping
LLM/VLM/RERANKERhere makes existing CLI scripts tokenize differently even though this PR is supposed to be non-breaking. Accept the legacy spellings as aliases to the new tokens for at least one compatibility window.Suggested compatibility patch
case "CHAT": return Token{Type: TokenChat, Value: ident} + case "LLM": + return Token{Type: TokenChat, Value: ident} case "THINK": return Token{Type: TokenThink, Value: ident} @@ case "VISION": return Token{Type: TokenVision, Value: ident} + case "VLM": + return Token{Type: TokenVision, Value: ident} case "EMBEDDING": return Token{Type: TokenEmbedding, Value: ident} case "RERANK": return Token{Type: TokenRerank, Value: ident} + case "RERANKER": + return Token{Type: TokenRerank, Value: ident}🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/cli/lexer.go` around lines 181 - 341, The lookupIdent function drops legacy model-type keywords causing breaking tokenization; add alias cases for "LLM" (map to TokenModel), "VLM" (map to TokenVision) and "RERANKER" (map to TokenRerank) so old CLI scripts continue to tokenize to the new tokens — update the switch in lookupIdent to include these uppercase string cases returning Token{Type: TokenModel, Value: ident}, Token{Type: TokenVision, Value: ident}, and Token{Type: TokenRerank, Value: ident} respectively (preserving Value as ident) to maintain backwards compatibility for at least one compatibility window.internal/entity/model.go (1)
335-350:⚠️ Potential issue | 🟠 Major
GetModelUrlstill rejects the new model types.After this PR, configs can advertise types like
visionandasr, but this switch still only resolveschat,async_chat,embedding, andrerank. Those models will pass the earlier capability check and then fail here with “does not support model type”.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/entity/model.go` around lines 335 - 350, GetModelUrl's switch on modelType only handles chat/async_chat/embedding/rerank, so newly advertised types like "vision" and "asr" will reach the default error; add explicit cases for those types (e.g., "vision", "asr") that construct and return the appropriate URLs using provider.URL and the matching provider.URLSuffix fields (e.g., provider.URLSuffix.Vision, provider.URLSuffix.ASR) similar to the existing cases, and ensure async-like types return both chat/result where applicable; update the switch in GetModelUrl to include these new case labels and return the constructed URL pointers instead of falling through to the default error referencing modelName and modelType.internal/service/tenant.go (1)
552-557:⚠️ Potential issue | 🟠 MajorError from
tenantDAO.Updateis ignored.The error returned by
s.tenantDAO.Update()is assigned but never checked. The function always returnsnilregardless of whether the update succeeded, which could silently fail to persist the default model change.🐛 Proposed fix to return the error
err = s.tenantDAO.Update(ownedTenant.TenantID, map[string]interface{}{ modelTypeID: defaultModel, }) - return nil + return err }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/service/tenant.go` around lines 552 - 557, The call to s.tenantDAO.Update(ownedTenant.TenantID, map[string]interface{}{ modelTypeID: defaultModel }) assigns an error to err but never checks or returns it; update failures are currently swallowed. Modify the surrounding function to check the returned error from s.tenantDAO.Update and propagate it (e.g., if err != nil { return err }) instead of unconditionally returning nil, ensuring the error from Update is handled and returned to callers.internal/cli/user_parser.go (1)
1633-1648:⚠️ Potential issue | 🟠 MajorDouble
p.nextToken()will skip a token, causing parse errors.After parsing
compositeModelNameat line 1633,p.nextToken()is called at line 1637 to advance past the quoted string. However, anotherp.nextToken()is called at line 1643 before checking for a semicolon. This causes the parser to skip a token, which will likely result in parse errors or incorrect semicolon handling.🐛 Proposed fix to remove redundant nextToken()
compositeModelName, err = p.parseQuotedString() if err != nil { return nil, err } p.nextToken() cmd := NewCommand("set_default_model") cmd.Params["model_type"] = modelType cmd.Params["composite_model_name"] = compositeModelName - p.nextToken() // Semicolon is optional for UNSET TOKEN if p.curToken.Type == TokenSemicolon { p.nextToken() } return cmd, nil🤖 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 1633 - 1648, The parser advances twice after parsing the quoted composite model name which skips one token and breaks semicolon handling; in the SetDefaultModel flow (after parseQuotedString and creation of NewCommand("set_default_model") with Params["model_type"] and Params["composite_model_name"]) remove the redundant p.nextToken() that occurs immediately before the TokenSemicolon check so that only the single p.nextToken() after parseQuotedString is used and the subsequent semicolon check (p.curToken.Type == TokenSemicolon) inspects the correct token.
♻️ Duplicate comments (1)
internal/entity/model.go (1)
148-150:⚠️ Potential issue | 🔴 CriticalResolve
Provider.URLto a concrete string before reusing it.
Provider.URLis now a region→URL map, but these call sites still treat it as a scalar.GetModelUrlwill build malformed endpoints from%s, and the list/show payloads now expose an object where callers previously got a single URL string. That is both a runtime break and an API-shape break for a PR marked non-breaking.Also applies to: 251-255, 275-278, 321-347
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/entity/model.go` around lines 148 - 150, Provider.URL was changed from string to map[string]string but call sites (notably GetModelUrl, list/show payload builders and places around the Provider struct usage) still treat it as a scalar; update these to resolve a concrete URL string before reuse by extracting the appropriate region key (or a defined default region) from the map. Specifically, modify GetModelUrl to accept a region (or use a defaultRegion constant) and look up provider.URL[region] (with a fallback if missing) before formatting with URLSuffix; update any payload builders that return provider.URL to return the resolved string instead of the map; and ensure all usages that previously passed provider.URL into fmt.Sprintf or string concatenation now pass the resolved string (search for GetModelUrl, Provider.URL, URLSuffix, and the list/show payload functions mentioned). Ensure graceful fallback/logging when the requested region key is absent.
🧹 Nitpick comments (3)
internal/cli/user_command.go (1)
1420-1428: Extract composite model parsing into one helper.The same
provider/instance/modelsplit and validation now lives in bothChatToModelandUseModel. A shared helper would keep future format changes and error messages consistent.Also applies to: 1527-1535
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/cli/user_command.go` around lines 1420 - 1428, Extract the repeated provider/instance/model parsing into a single helper function (e.g., ParseCompositeModelName) and replace the duplicated parsing blocks in ChatToModel and UseModel with calls to that helper; the helper should accept the composite_model_name string, validate the format (exactly three parts separated by '/'), and return providerName, instanceName, modelName and a descriptive error if invalid so both ChatToModel and UseModel use the same validation and error message.internal/cli/admin_parser.go (1)
1248-1285: Syntax inconsistency: RESET DEFAULT command requires MODEL keyword in user parser but not admin parser.The admin parser accepts
RESET DEFAULT CHAT;while the user parser requiresRESET DEFAULT CHAT MODEL;. Both parsers handle the model type the same way after theDEFAULTkeyword, but the user parser mandates aMODELkeyword before the optional semicolon, whereas the admin parser does not.Consider aligning both parsers to use the same syntax.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/cli/admin_parser.go` around lines 1248 - 1285, The admin parser's parseAdminResetCommand currently accepts "RESET DEFAULT <model>;" without the MODEL keyword, causing a syntax mismatch with the user parser; update parseAdminResetCommand to require and consume TokenModel after the model type (i.e., after setting cmd.Params["model_type"]) before allowing the optional TokenSemicolon, mirroring the user parser's behavior so both parsers accept "RESET DEFAULT CHAT MODEL;" consistently (adjust token checks around p.nextToken(), TokenModel, and the optional TokenSemicolon near NewCommand("reset_default_model")).internal/service/tenant.go (1)
329-333: Hardcoded OCR model bypasses validation - consider making this configurable.The special case for
infiniflow/default/deepdocOCR model returns immediately without any DAO lookups. While this may be intentional for a built-in model, hardcoding the provider/instance/model names makes it fragile to configuration changes.Consider extracting these values to constants or configuration to improve maintainability.
🤖 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 - 333, The code in the model selection branch special-cases providerName/instanceName/modelName for OCR by hardcoding "infiniflow"/"default"/"deepdoc"; replace that fragile literal check with a configurable constant or config-driven values (e.g., DEFAULT_OCR_PROVIDER, DEFAULT_OCR_INSTANCE, DEFAULT_OCR_MODEL) and read them from the tenant/service configuration or environment, then update the modelType == "ocr" branch (the block using providerName, instanceName, modelName) to compare against those constants/config values instead of raw strings so the bypass remains but is maintainable and configurable.
🤖 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/cli/common_command.go`:
- Around line 383-386: The error message when extracting compositeModelName from
cmd.Params is wrong; update the fmt.Errorf call in the block that checks
composite_model_name (where compositeModelName, ok :=
cmd.Params["composite_model_name"].(string)) to return an error that references
"composite_model_name not provided" (or similar) so the message matches the
actual parameter being validated.
In `@internal/entity/tenant.go`:
- Around line 37-38: Add a DB migration in internal/dao/migration.go that adds
the two new tenant columns and backfills existing rows: add ocr_id VARCHAR(256)
and tenant_ocr_id BIGINT; for existing tenant rows populate tenant.ocr_id with a
non-NULL value (e.g. a generated UUID or deterministic placeholder per row)
before altering tenant.ocr_id to NOT NULL; leave tenant_ocr_id nullable.
Register this migration in the same migration registration function used by
other migrations so it runs on upgrade; after deploying the migration the code
that scans OCRID/TenantOCRID (see struct fields OCRID and TenantOCRID in
internal/entity/tenant.go and the tenant DAO that scans tenant.ocr_id in
internal/dao/tenant.go) will succeed.
---
Outside diff comments:
In `@internal/cli/lexer.go`:
- Around line 181-341: The lookupIdent function drops legacy model-type keywords
causing breaking tokenization; add alias cases for "LLM" (map to TokenModel),
"VLM" (map to TokenVision) and "RERANKER" (map to TokenRerank) so old CLI
scripts continue to tokenize to the new tokens — update the switch in
lookupIdent to include these uppercase string cases returning Token{Type:
TokenModel, Value: ident}, Token{Type: TokenVision, Value: ident}, and
Token{Type: TokenRerank, Value: ident} respectively (preserving Value as ident)
to maintain backwards compatibility for at least one compatibility window.
In `@internal/cli/user_parser.go`:
- Around line 1633-1648: The parser advances twice after parsing the quoted
composite model name which skips one token and breaks semicolon handling; in the
SetDefaultModel flow (after parseQuotedString and creation of
NewCommand("set_default_model") with Params["model_type"] and
Params["composite_model_name"]) remove the redundant p.nextToken() that occurs
immediately before the TokenSemicolon check so that only the single
p.nextToken() after parseQuotedString is used and the subsequent semicolon check
(p.curToken.Type == TokenSemicolon) inspects the correct token.
In `@internal/entity/model.go`:
- Around line 335-350: GetModelUrl's switch on modelType only handles
chat/async_chat/embedding/rerank, so newly advertised types like "vision" and
"asr" will reach the default error; add explicit cases for those types (e.g.,
"vision", "asr") that construct and return the appropriate URLs using
provider.URL and the matching provider.URLSuffix fields (e.g.,
provider.URLSuffix.Vision, provider.URLSuffix.ASR) similar to the existing
cases, and ensure async-like types return both chat/result where applicable;
update the switch in GetModelUrl to include these new case labels and return the
constructed URL pointers instead of falling through to the default error
referencing modelName and modelType.
In `@internal/service/tenant.go`:
- Around line 552-557: The call to s.tenantDAO.Update(ownedTenant.TenantID,
map[string]interface{}{ modelTypeID: defaultModel }) assigns an error to err but
never checks or returns it; update failures are currently swallowed. Modify the
surrounding function to check the returned error from s.tenantDAO.Update and
propagate it (e.g., if err != nil { return err }) instead of unconditionally
returning nil, ensuring the error from Update is handled and returned to
callers.
---
Duplicate comments:
In `@internal/entity/model.go`:
- Around line 148-150: Provider.URL was changed from string to map[string]string
but call sites (notably GetModelUrl, list/show payload builders and places
around the Provider struct usage) still treat it as a scalar; update these to
resolve a concrete URL string before reuse by extracting the appropriate region
key (or a defined default region) from the map. Specifically, modify GetModelUrl
to accept a region (or use a defaultRegion constant) and look up
provider.URL[region] (with a fallback if missing) before formatting with
URLSuffix; update any payload builders that return provider.URL to return the
resolved string instead of the map; and ensure all usages that previously passed
provider.URL into fmt.Sprintf or string concatenation now pass the resolved
string (search for GetModelUrl, Provider.URL, URLSuffix, and the list/show
payload functions mentioned). Ensure graceful fallback/logging when the
requested region key is absent.
---
Nitpick comments:
In `@internal/cli/admin_parser.go`:
- Around line 1248-1285: The admin parser's parseAdminResetCommand currently
accepts "RESET DEFAULT <model>;" without the MODEL keyword, causing a syntax
mismatch with the user parser; update parseAdminResetCommand to require and
consume TokenModel after the model type (i.e., after setting
cmd.Params["model_type"]) before allowing the optional TokenSemicolon, mirroring
the user parser's behavior so both parsers accept "RESET DEFAULT CHAT MODEL;"
consistently (adjust token checks around p.nextToken(), TokenModel, and the
optional TokenSemicolon near NewCommand("reset_default_model")).
In `@internal/cli/user_command.go`:
- Around line 1420-1428: Extract the repeated provider/instance/model parsing
into a single helper function (e.g., ParseCompositeModelName) and replace the
duplicated parsing blocks in ChatToModel and UseModel with calls to that helper;
the helper should accept the composite_model_name string, validate the format
(exactly three parts separated by '/'), and return providerName, instanceName,
modelName and a descriptive error if invalid so both ChatToModel and UseModel
use the same validation and error message.
In `@internal/service/tenant.go`:
- Around line 329-333: The code in the model selection branch special-cases
providerName/instanceName/modelName for OCR by hardcoding
"infiniflow"/"default"/"deepdoc"; replace that fragile literal check with a
configurable constant or config-driven values (e.g., DEFAULT_OCR_PROVIDER,
DEFAULT_OCR_INSTANCE, DEFAULT_OCR_MODEL) and read them from the tenant/service
configuration or environment, then update the modelType == "ocr" branch (the
block using providerName, instanceName, modelName) to compare against those
constants/config values instead of raw strings so the bypass remains but is
maintainable and configurable.
🪄 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: cd343e20-eff6-4b5d-8041-18369b4cfbe2
📒 Files selected for processing (15)
conf/models/openai.jsonconf/models/xai.jsonconf/models/zhipu-ai.jsoninternal/cli/admin_parser.gointernal/cli/client.gointernal/cli/common_command.gointernal/cli/lexer.gointernal/cli/types.gointernal/cli/user_command.gointernal/cli/user_parser.gointernal/dao/tenant.gointernal/entity/model.gointernal/entity/tenant.gointernal/handler/tenant.gointernal/service/tenant.go
🚧 Files skipped from review as they are similar to previous changes (1)
- conf/models/xai.json
| compositeModelName, ok := cmd.Params["composite_model_name"].(string) | ||
| if !ok { | ||
| return nil, fmt.Errorf("model_name not provided") | ||
| } |
There was a problem hiding this comment.
Misleading error message - refers to wrong parameter name.
The error message says "model_name not provided" but the actual parameter being checked is composite_model_name. This could confuse users debugging CLI issues.
📝 Proposed fix for error message
compositeModelName, ok := cmd.Params["composite_model_name"].(string)
if !ok {
- return nil, fmt.Errorf("model_name not provided")
+ return nil, fmt.Errorf("composite_model_name not provided")
}📝 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.
| compositeModelName, ok := cmd.Params["composite_model_name"].(string) | |
| if !ok { | |
| return nil, fmt.Errorf("model_name not provided") | |
| } | |
| compositeModelName, ok := cmd.Params["composite_model_name"].(string) | |
| if !ok { | |
| return nil, fmt.Errorf("composite_model_name not provided") | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/cli/common_command.go` around lines 383 - 386, The error message
when extracting compositeModelName from cmd.Params is wrong; update the
fmt.Errorf call in the block that checks composite_model_name (where
compositeModelName, ok := cmd.Params["composite_model_name"].(string)) to return
an error that references "composite_model_name not provided" (or similar) so the
message matches the actual parameter being validated.
| OCRID string `gorm:"column:ocr_id;size:256;not null" json:"ocr_id"` | ||
| TenantOCRID *int64 `gorm:"column:tenant_ocr_id" json:"tenant_ocr_id,omitempty"` |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf 'Searching for OCR-related tenant schema changes...\n'
rg -n -C2 '\bocr_id\b|\btenant_ocr_id\b' .
printf '\nSearching for tenant-table migrations/backfills...\n'
rg -n -C2 'ALTER TABLE.*tenant|CREATE TABLE.*tenant|AutoMigrate\(&entity\.Tenant|Migrator\(\).*AddColumn|Migrator\(\).*HasColumn|UPDATE\s+tenant\s+SET\s+ocr_id' .Repository: infiniflow/ragflow
Length of output: 9708
🏁 Script executed:
cat -n internal/dao/migration.go | head -100Repository: infiniflow/ragflow
Length of output: 3948
🏁 Script executed:
wc -l internal/dao/migration.goRepository: infiniflow/ragflow
Length of output: 91
🏁 Script executed:
cat -n internal/dao/migration.goRepository: infiniflow/ragflow
Length of output: 13205
Missing migration for tenant.ocr_id and tenant.tenant_ocr_id columns.
OCRID is marked not null in the schema, and the code at internal/dao/tenant.go:75 now scans tenant.ocr_id into a plain string field. No migration exists in internal/dao/migration.go to add these columns or backfill existing rows. On upgrade, tenant reads and inserts will fail if the column is missing or NULL.
Add a migration step to:
- Create both columns (
ocr_idVARCHAR(256) NOT NULL,tenant_ocr_idBIGINT) - Set a default/backfill value for existing tenant rows before this code is deployed
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/tenant.go` around lines 37 - 38, Add a DB migration in
internal/dao/migration.go that adds the two new tenant columns and backfills
existing rows: add ocr_id VARCHAR(256) and tenant_ocr_id BIGINT; for existing
tenant rows populate tenant.ocr_id with a non-NULL value (e.g. a generated UUID
or deterministic placeholder per row) before altering tenant.ocr_id to NOT NULL;
leave tenant_ocr_id nullable. Register this migration in the same migration
registration function used by other migrations so it runs on upgrade; after
deploying the migration the code that scans OCRID/TenantOCRID (see struct fields
OCRID and TenantOCRID in internal/entity/tenant.go and the tenant DAO that scans
tenant.ocr_id in internal/dao/tenant.go) will succeed.
### What problem does this PR solve? Now each model support region with different URL ### Type of change - [x] New Feature (non-breaking change which adds functionality) --------- Signed-off-by: Jin Hai <[email protected]>
What problem does this PR solve?
Now each model support region with different URL
Type of change