Skip to content

Refactor model in GO - #14398

Merged
JinHai-CN merged 3 commits into
infiniflow:mainfrom
qinling0210:refactor_go_model
Apr 28, 2026
Merged

JinHai-CN merged 3 commits into
infiniflow:mainfrom
qinling0210:refactor_go_model

Conversation

@qinling0210

@qinling0210 qinling0210 commented Apr 27, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Refactor model in GO

Type of change

  • Refactoring

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

coderabbitai Bot commented Apr 27, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Replaces the factory/registry model-provider pattern with typed wrapper models and a ModelProviderService; extends ModelDriver interface with Encode/EncodeQuery/Rerank; implements Siliconflow embedding and rerank; adds convenience methods on multiple model drivers and updates service/handler signatures and routing to use model-name wildcards.

Changes

Cohort / File(s) Summary
Configuration
conf/models/zhipu-ai.json
Change url_suffix.embedding from "embedding" to "embeddings".
Core model interface & wrappers
internal/entity/models/types.go, internal/entity/types.go
Add Encode, EncodeQuery, Rerank to ModelDriver; introduce EmbeddingModel, RerankModel, ChatModel wrappers and updated interface signatures accepting modelName *string and apiConfig *APIConfig.
Siliconflow implementation
internal/entity/models/siliconflow.go, conf/models/siliconflow.json
Add full EncodeToEmbedding implementation, Rerank implementation and request/response types; register Qwen embedding model config entry.
Zhipu driver updates
internal/entity/models/zhipu-ai.go, conf/models/zhipu-ai.json
Use dynamic URL suffix fields for chat/embedding endpoints; add Encode, EncodeQuery, Rerank convenience methods (Rerank returns not-implemented).
Added convenience stubs across drivers
internal/entity/models/google.go, internal/entity/models/aliyun.go, internal/entity/models/deepseek.go, internal/entity/models/dummy.go, internal/entity/models/gitee.go, internal/entity/models/minimax.go, internal/entity/models/moonshot.go
Add Encode, EncodeQuery, Rerank methods; most are thin wrappers or error stubs indicating "not implemented".
Provider factory removal
internal/service/models/factory.go, internal/service/models/*.go (deleted: deepseek_model.go, gitee_model.go, moonshot_model.go, openai_model.go, openai_api_compatible_model.go, siliconflow_model.go, zhipu_model.go)
Remove global factory registry and per-provider init-time registrations for many providers.
Model provider/service refactor
internal/service/model_service.go, internal/service/model_bundle.go
Remove old ModelProvider interface/impl; add ModelProviderService.Get{Embedding,Chat,Rerank}Model() returning typed wrapper models and centralize model/instance/apiConfig resolution; ModelBundle stores APIConfig and delegates calls with modelName/APIConfig.
Service & NLP updates
internal/service/chunk.go, internal/service/nlp/retrieval.go, internal/service/nlp/reranker.go, internal/service/model_bundle.go
Switch from untyped interfaces to *models.EmbeddingModel / *models.RerankModel; update GetVector, retrieval and reranker call sites to invoke driver methods with modelName and APIConfig; rename Similarity→Rerank.
Routing & handler tweaks
internal/router/router.go, internal/handler/providers.go
Allow model_name as wildcard path (*model_name) and strip leading / in handler before validation.
Other small updates
multiple files
Signature and call-site adjustments across services to propagate new method signatures and APIConfig where needed.
sequenceDiagram
  participant API as "API / Handler"
  participant ProviderSvc as "ModelProviderService"
  participant DAO as "DAO (tenant/provider/instance)"
  participant Wrapper as "models.EmbeddingModel / RerankModel"
  participant Driver as "ModelDriver (provider)"
  participant External as "External Model API"

  API->>ProviderSvc: GetEmbeddingModel(tenant, compositeName)
  ProviderSvc->>DAO: Resolve tenant / provider / instance
  DAO-->>ProviderSvc: Model config + API key / region
  ProviderSvc->>Wrapper: NewEmbeddingModel(driver, modelName, apiConfig)
  API->>Wrapper: EncodeQuery(&modelName, query, apiConfig)
  Wrapper->>Driver: ModelDriver.EncodeQuery(&modelName, query, apiConfig)
  Driver->>External: HTTP request (provider API)
  External-->>Driver: embeddings / rerank response
  Driver-->>Wrapper: []float64 embedding / []float64 scores
  Wrapper-->>API: result
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

🐰 I swapped the registry for wrappers bright,
Names and configs tucked in tight,
Embeddings hum, reranks await,
A tidy hop through code and state,
Tiny paws applaud this refactor night.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Description check ⚠️ Warning The pull request description provides minimal context. It only contains a checkbox selection and vague problem statement without explaining what was refactored, why, or how the changes align with the massive scope of modifications across the model system. Expand the description to explain: (1) the old model architecture and its limitations, (2) the new architecture and its benefits, (3) key structural changes (e.g., factory pattern removal, wrapper types introduction), and (4) migration impact on dependent services.
Title check ❓ Inconclusive The title "Refactor model in GO" is vague and generic, using non-descriptive language that doesn't convey the specific scope or nature of the refactoring across 20+ model-related files. Provide a more specific title that describes the main refactoring objective, such as "Refactor model driver abstraction and service architecture" or "Migrate from factory pattern to wrapper-based model instances".
✅ Passed checks (3 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring coverage is 92.31% 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 marked this pull request as ready for review April 27, 2026 09:30
@dosubot dosubot Bot added the size:XXL This PR changes 1000+ lines, ignoring generated files. label Apr 27, 2026
@qinling0210
qinling0210 requested a review from JinHai-CN April 27, 2026 09:30

@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: 9

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
internal/entity/models/factory.go (1)

33-53: ⚠️ Potential issue | 🟠 Major

Asymmetric modelName handling causes embedding requests with empty model field.

Both zhipu-ai and siliconflow store ModelName in the driver struct, but their embedding methods (EncodeToEmbedding) ignore the modelName parameter and use the constructor-time field instead—unlike their Chat methods, which correctly use the parameter. When CreateModelDriver is called with modelName="" (as in internal/entity/model.go:274), the driver stores an empty string, and any subsequent Encode() call produces a request with "model": "" in the body.

This is inconsistent and error-prone. Consider one of:

  1. Stop storing ModelName on the driver. Use the method-provided modelName in both Chat and embedding methods—they already take it as a parameter.
  2. Validate at construction time: return an error when "zhipu-ai" or "siliconflow" is created with an empty modelName.

Option 1 is cleaner because it unifies the pattern: always pass modelName at call time, never store it.

Also consider: the default: case returns a DummyModel for unknown providers, silently masking typos in configuration. Returning an error instead would be safer.

🤖 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 - 53, CreateModelDriver
stores modelName in NewZhipuAIModel/NewSiliconflowModel which leads to empty
"model" fields for embeddings when modelName==""; change the drivers to stop
persisting ModelName and have Encode/EncodeToEmbedding use the modelName
parameter passed into the methods (remove reliance on the constructor field), or
alternatively validate in CreateModelDriver and return an error for "zhipu-ai"
and "siliconflow" when modelName==""; also replace the silent fallback in the
default case (NewDummyModel) with returning an explicit error to surface unknown
provider names. Ensure you touch CreateModelDriver, NewZhipuAIModel,
NewSiliconflowModel, the driver structs' ModelName field, and
Encode/EncodeToEmbedding implementations to apply the chosen fix.
internal/service/model_bundle.go (1)

68-73: ⚠️ Potential issue | 🟠 Major

Don’t discard apiConfig for rerank — rerank requires the API key to call the provider.

The third return from provider.GetRerankModel carries the API key/region needed by ModelDriver.Rerank. Discarding it here means even a fixed RerankModel interface won’t have credentials available when (*ModelBundle).Rerank runs. Embedding and chat correctly capture and store it on the bundle — rerank should too.

(Root cause for the broken type assertion downstream is filed against internal/entity/types.go RerankModel definition.)

🔧 Proposed fix
 case entity.ModelTypeRerank:
-    rerankModel, _, err := provider.GetRerankModel(context.Background(), tenantID, bundle.modelName)
+    rerankModel, apiConfig, err := provider.GetRerankModel(context.Background(), tenantID, bundle.modelName)
     if err != nil {
         return nil, fmt.Errorf("failed to get rerank model: %w", err)
     }
     bundle.model = rerankModel
+    bundle.apiConfig = apiConfig
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/service/model_bundle.go` around lines 68 - 73, The code discards the
third return (apiConfig) from provider.GetRerankModel, leaving credentials
unavailable when ModelBundle.Rerank runs; update the case handling in
ModelBundle where GetRerankModel is called to capture the third return value
(apiConfig) and store it on the bundle (same field used by embedding/chat
storage) in addition to assigning bundle.model, so the Rerank flow has the
provider API key/region available.
internal/entity/models/zhipu-ai.go (1)

439-455: ⚠️ Potential issue | 🟠 Major

Major: EncodeToEmbedding silently ignores its modelName parameter.

The function accepts modelName *string but uses z.ModelName for the request body (line 455). Any caller that passes a different model name will be ignored—a quiet correctness footgun. This is inconsistent with other methods in the same provider (e.g., Chat, ChatStream) which honor the modelName parameter. Note that SiliconflowModel exhibits the same pattern, suggesting a possible deliberate design choice; however, the per-call parameter should either be honored when provided or removed from the signature to clarify the contract.

Fix: When modelName is provided and non-empty, use it; otherwise fall back to z.ModelName.

-		reqBody := map[string]interface{}{
-			"model": z.ModelName,
+		resolvedModel := z.ModelName
+		if modelName != nil && *modelName != "" {
+			resolvedModel = *modelName
+		}
+		reqBody := map[string]interface{}{
+			"model": resolvedModel,
🤖 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 439 - 455, In
EncodeToEmbedding, the function currently ignores the modelName parameter and
always uses z.ModelName; update the request body construction in
EncodeToEmbedding so that if the pointer modelName is non-nil and non-empty it
is used, otherwise fall back to z.ModelName (mirror the pattern used in
Chat/ChatStream); locate EncodeToEmbedding and the map entry "model":
z.ModelName and replace it with a conditional choice using modelName when
provided.
🧹 Nitpick comments (5)
internal/service/chunk.go (1)

371-381: Possible variable shadowing inside the else if branch.

Line 372 declares var err error, which shadows the outer err returned from earlier calls. As a result, err set at lines 373/377 will not be visible to any outer code that may inspect err (none here today, but easy to break later). The first branch (lines 358-370) does not redeclare err and uses = directly, so the two branches are inconsistent.

If this was pre-existing, no change is required — flagging only because the surrounding lines are part of this PR. Consider removing the inner var err error to make both branches consistent:

♻️ Suggested cleanup
 	} else if req.RerankID != nil && *req.RerankID != "" {
-		var err error
 		_, rerankCompositeName, err = dao.LookupTenantLLMByName(dao.NewTenantLLMDAO(), tenantIDs[0], *req.RerankID, entity.ModelTypeRerank)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/service/chunk.go` around lines 371 - 381, The else-if branch
declares a new local "var err error" which shadows the outer err; remove that
declaration and use existing err (i.e., use "=" assignments for the calls to
dao.LookupTenantLLMByName and s.modelProvider.GetRerankModel) so the error
variable is consistent with the first branch and avoids accidental shadowing
around req.RerankID handling.
internal/entity/models/types.go (1)

9-10: Stale comment on ModelDriver interface.

The doc comment says "EmbeddingModel interface for embedding models" but the type is ModelDriver and it spans chat, embedding, rerank, listing, balance, and connection-checking. Worth correcting to avoid confusing readers, especially since this PR widens the interface further.

📝 Suggested doc fix
-// EmbeddingModel interface for embedding models
+// ModelDriver is the unified interface implemented by every provider driver
+// (chat, embedding, rerank, listing, balance, and connectivity).
 type ModelDriver interface {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/entity/models/types.go` around lines 9 - 10, Update the stale doc
comment above the ModelDriver type to accurately describe the interface's scope:
replace "EmbeddingModel interface for embedding models" with a concise
description mentioning that ModelDriver is an interface for model drivers (chat,
embedding, rerank, listing), plus balance and connection-checking operations;
ensure the comment sits immediately above the type ModelDriver declaration so
readers see the updated responsibility summary.
internal/entity/models/deepseek.go (1)

489-493: Nit: group Rerank with the other new convenience methods.

Same as minimax.go: Rerank is placed after CheckConnection, separated from Encode/EncodeQuery (lines 404-412). Moving it next to them improves consistency across provider files.

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

In `@internal/entity/models/deepseek.go` around lines 489 - 493, Move the Rerank
method on DeepSeekModel so it sits with the other convenience methods (near
Encode and EncodeQuery) rather than after CheckConnection; specifically locate
the Rerank function (func (z *DeepSeekModel) Rerank) and cut/paste it to be
adjacent to Encode and EncodeQuery in deepseek.go to match the placement used in
minimax.go for consistency across provider files.
internal/entity/models/minimax.go (1)

125-130: Nit: place Rerank next to Encode/EncodeQuery for readability.

Rerank is appended at the very end of the file, after CheckConnection, while Encode/EncodeQuery are grouped near EncodeToEmbedding (lines 74-82). Co-locating all three new convenience methods keeps the file consistent with the other provider files in this PR (e.g., gitee.go, deepseek.go).

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

In `@internal/entity/models/minimax.go` around lines 125 - 130, The Rerank method
for MinimaxModel is placed far from the related embedding helpers; move the
Rerank function declaration so it sits adjacent to Encode, EncodeQuery, and
EncodeToEmbedding within the MinimaxModel block (near where Encode/EncodeQuery
are defined) rather than after CheckConnection, preserving the same function
signature (func (z *MinimaxModel) Rerank(query string, texts []string, apiConfig
*APIConfig) ([]float64, error)) and keeping MinimaxModel methods grouped for
readability and consistency with other provider files.
internal/service/model_service.go (1)

70-117: Refactor: extract a single helper for the duplicated provider-resolution logic.

The same ~50 lines (parse name → fetch TenantLLM → resolve apiBase → load ProviderManager → CreateModelDriver) appear three times. Beyond DRY, every call also re-parses conf/models/*.json from disk via entity.NewProviderManager("conf/models") per request — for chat/embedding/rerank, this is on a hot retrieval path. Cache the manager once at startup (or memoize) and consolidate the per-request work.

♻️ Sketch
var providerManagerOnce sync.Once
var providerManager *entity.ProviderManager
var providerManagerErr error

func getProviderManager() (*entity.ProviderManager, error) {
    providerManagerOnce.Do(func() {
        providerManager, providerManagerErr = entity.NewProviderManager("conf/models")
    })
    return providerManager, providerManagerErr
}

func (p *ModelProviderImpl) buildDriver(tenantID, compositeName string) (modelModule.ModelDriver, *modelModule.APIConfig, error) {
    modelName, provider, err := parseModelName(compositeName)
    if err != nil {
        return nil, nil, err
    }
    tenantLLM, err := dao.NewTenantLLMDAO().GetByTenantFactoryAndModelName(tenantID, provider, modelName)
    if err != nil {
        return nil, nil, err
    }
    if tenantLLM.APIKey == nil || *tenantLLM.APIKey == "" {
        return nil, nil, fmt.Errorf("no API key found for tenant %s and model %s", tenantID, compositeName)
    }
    pm, err := getProviderManager()
    if err != nil || pm == nil {
        return nil, nil, fmt.Errorf("failed to load provider manager: %w", err)
    }
    pe := pm.FindProvider(strings.ToLower(provider))
    if pe == nil {
        return nil, nil, fmt.Errorf("provider %s not found in conf/models", provider)
    }
    // ... apply tenant override, build driver, return.
}

Also applies to: 120-167, 170-216

🤖 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 70 - 117, The
GetEmbeddingModel/ChatModel/GetRerankModel blocks duplicate ~50 lines
(parseModelName → TenantLLM lookup → resolve apiBase → entity.NewProviderManager
→ CreateModelDriver) and re-read conf/models per request; extract this into a
single helper on ModelProviderImpl (e.g., buildDriver or resolveDriver) and
memoize the ProviderManager via a package-level getProviderManager using
sync.Once (as sketched). Replace the duplicated sequences in GetEmbeddingModel
(and the analogous methods at ~120-167 and ~170-216) to call the new helper; the
helper should call parseModelName,
dao.NewTenantLLMDAO().GetByTenantFactoryAndModelName, validate APIKey, resolve
apiBase using dao.NewModelProviderDAO() fallback, obtain the cached
ProviderManager (entity.NewProviderManager via getProviderManager), find
providerEntity, and invoke modelModule.NewModelFactory().CreateModelDriver,
returning (modelModule.ModelDriver, *modelModule.APIConfig, error).
🤖 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 274-277: The provider-level driver is being created with an empty
modelName (CreateModelDriver(..., "")) which leaves ZhipuAIModel.ModelName and
SiliconflowModel.ModelName empty and breaks calls like Balance(),
CheckConnection(), and EncodeToEmbedding; fix by passing the provider's
configured default model name when constructing the provider driver (e.g. use
provider.DefaultModel or provider.ModelName — whichever field holds the
provider's default model) instead of "", or change CreateModelDriver usage to
construct drivers per-request with the correct model name so NewZhipuAIModel and
NewSiliconflowModel receive the actual modelName.

In `@internal/entity/models/aliyun.go`:
- Around line 340-353: The Encode, EncodeQuery, and Rerank methods on
AliyunModel are unimplemented stubs (functions Encode, EncodeQuery, Rerank on
type AliyunModel) and will panic if an embedding/rerank model is ever selected;
either implement these methods or guard model selection at runtime. Fix by
adding a runtime check in the AliyunModel request path (or in the code that
chooses models using aliyun.json) that validates the requested model supports
embeddings/rerank and returns a clear error if not supported, or implement
proper embedding/rerank logic inside AliyunModel.Encode,
AliyunModel.EncodeQuery, and AliyunModel.Rerank so they call the correct Aliyun
embedding endpoints and return embeddings; ensure the error messages reference
z.Name() and explicitly state unsupported model types so future config changes
won’t select unsupported model types.

In `@internal/entity/models/moonshot.go`:
- Around line 76-84: The Moonshot embedding/rerank methods Encode, EncodeQuery,
and Rerank on MoonshotModel are only stubs and will cause runtime failures; fix
by either (A) implementing the real HTTP calls: use APIConfig in
MoonshotModel.Encode and EncodeQuery to POST to Moonshot's embedding endpoint,
parse and return [][]float64 / []float64 with proper error handling and
timeouts, and implement MoonshotModel.Rerank to call the rerank endpoint and map
scores back to the expected signature, or (B) if deferring, gate Moonshot
selection in the retrieval/reranker flow and replace these stubs with explicit
"feature disabled" errors plus a reference to a tracking issue ID and a TODO
comment so callers cannot select Moonshot; update any selection logic that
references MoonshotModel to respect the gate.

In `@internal/entity/models/siliconflow.go`:
- Around line 605-611: The code currently ignores the error from
io.ReadAll(resp.Body) causing transport/read failures to be masked by
json.Unmarshal; update the block around io.ReadAll(resp.Body) to handle and
return the read error (or use json.NewDecoder(resp.Body).Decode(&rerankResp) as
EncodeToEmbedding does) so that failures surface correctly; specifically, check
the error returned by io.ReadAll (or replace with streaming json.Decoder) before
calling json.Unmarshal on SiliconflowRerankResponse.
- Around line 470-478: The EncodeQuery method may return a nil slice when the
upstream embedding response lacked data for index 0; update
SiliconflowModel.EncodeQuery to validate that embeddings is non-nil, has length
> 0, and that embeddings[0] is non-nil/has non-zero length before returning it,
and return a descriptive error (e.g. "no embedding returned for query") if the
guard fails; use the existing Encode call and the embeddings variable to locate
the check and error path.
- Around line 401-462: The EncodeToEmbedding implementation in SiliconflowModel
ignores the modelName parameter and allows negative data.Index to panic; update
SiliconflowModel.EncodeToEmbedding to choose the model like: if modelName != nil
&& *modelName != "" then use *modelName else fallback to s.ModelName when
building reqBody.Model, and in the loop that iterates embeddingResp.Data only
assign embeddings if data.Index >= 0 && data.Index < len(embeddings) (check both
bounds) to match the Rerank guard and avoid negative-index panics; refer to
symbols EncodeToEmbedding, modelName, s.ModelName, reqBody.Model,
embeddingResp.Data, data.Index, and embeddings.

In `@internal/entity/models/types.go`:
- Around line 19-26: The interface exposes EncodeToEmbedding, Encode and
EncodeQuery but several providers (Moonshot, Minimax, Gitee, DeepSeek, Aliyun,
Dummy) return "not implemented", causing runtime failures; update each
provider's Encode(texts []string, apiConfig *APIConfig) and EncodeQuery(query
string, apiConfig *APIConfig) implementations to delegate to their
EncodeToEmbedding(modelName *string, texts []string, apiConfig *APIConfig,
embeddingConfig *EmbeddingConfig) (for EncodeQuery wrap the single query into a
one-element slice and return the first embedding) — i.e., call
EncodeToEmbedding(nil, texts, apiConfig, nil) and convert results/errors
appropriately — so all providers follow the same delegation pattern as ZhipuAI
and SiliconflowModel.

In `@internal/entity/types.go`:
- Around line 60-63: The RerankModel interface signature is out of sync with
ModelDriver: change entity.RerankModel's Rerank to match
models.ModelDriver.Rerank(query string, texts []string, apiConfig *APIConfig)
([]float64, error) (or remove RerankModel and assert against
models.ModelDriver), then update ModelBundle usage to accept and forward the
returned apiConfig from GetRerankModel so the apiConfig is passed into the
Rerank call (fix code paths that do b.model.(entity.RerankModel) to use
models.ModelDriver or the updated interface and ensure apiConfig is not
discarded).

In `@internal/service/model_service.go`:
- Around line 105-117: The NewProviderManager call is ignoring its error
(causing possible nil-pointer panics) and tenant APIBase overrides are being
discarded when baseURLMap is unconditionally replaced by providerEntity.URL; fix
by checking and returning the error from entity.NewProviderManager (use:
NewProviderManager return values) before calling providerManager.FindProvider,
and then preserve tenant overrides by merging/choosing the API base correctly
instead of always overwriting baseURLMap — e.g., compute baseURLMap from
TenantLLM.APIBase or ModelProviderDAO.DefaultURL (symbols: TenantLLM.APIBase,
ModelProviderDAO.DefaultURL, baseURLMap) and only fallback to providerEntity.URL
when no tenant/default value exists, applying the same fixes in GetChatModel and
GetRerankModel and ensure providerEntity lookup only runs after successful
providerManager creation (symbols: providerManager, providerEntity,
NewProviderManager, providerManager.FindProvider).

---

Outside diff comments:
In `@internal/entity/models/factory.go`:
- Around line 33-53: CreateModelDriver stores modelName in
NewZhipuAIModel/NewSiliconflowModel which leads to empty "model" fields for
embeddings when modelName==""; change the drivers to stop persisting ModelName
and have Encode/EncodeToEmbedding use the modelName parameter passed into the
methods (remove reliance on the constructor field), or alternatively validate in
CreateModelDriver and return an error for "zhipu-ai" and "siliconflow" when
modelName==""; also replace the silent fallback in the default case
(NewDummyModel) with returning an explicit error to surface unknown provider
names. Ensure you touch CreateModelDriver, NewZhipuAIModel, NewSiliconflowModel,
the driver structs' ModelName field, and Encode/EncodeToEmbedding
implementations to apply the chosen fix.

In `@internal/entity/models/zhipu-ai.go`:
- Around line 439-455: In EncodeToEmbedding, the function currently ignores the
modelName parameter and always uses z.ModelName; update the request body
construction in EncodeToEmbedding so that if the pointer modelName is non-nil
and non-empty it is used, otherwise fall back to z.ModelName (mirror the pattern
used in Chat/ChatStream); locate EncodeToEmbedding and the map entry "model":
z.ModelName and replace it with a conditional choice using modelName when
provided.

In `@internal/service/model_bundle.go`:
- Around line 68-73: The code discards the third return (apiConfig) from
provider.GetRerankModel, leaving credentials unavailable when ModelBundle.Rerank
runs; update the case handling in ModelBundle where GetRerankModel is called to
capture the third return value (apiConfig) and store it on the bundle (same
field used by embedding/chat storage) in addition to assigning bundle.model, so
the Rerank flow has the provider API key/region available.

---

Nitpick comments:
In `@internal/entity/models/deepseek.go`:
- Around line 489-493: Move the Rerank method on DeepSeekModel so it sits with
the other convenience methods (near Encode and EncodeQuery) rather than after
CheckConnection; specifically locate the Rerank function (func (z
*DeepSeekModel) Rerank) and cut/paste it to be adjacent to Encode and
EncodeQuery in deepseek.go to match the placement used in minimax.go for
consistency across provider files.

In `@internal/entity/models/minimax.go`:
- Around line 125-130: The Rerank method for MinimaxModel is placed far from the
related embedding helpers; move the Rerank function declaration so it sits
adjacent to Encode, EncodeQuery, and EncodeToEmbedding within the MinimaxModel
block (near where Encode/EncodeQuery are defined) rather than after
CheckConnection, preserving the same function signature (func (z *MinimaxModel)
Rerank(query string, texts []string, apiConfig *APIConfig) ([]float64, error))
and keeping MinimaxModel methods grouped for readability and consistency with
other provider files.

In `@internal/entity/models/types.go`:
- Around line 9-10: Update the stale doc comment above the ModelDriver type to
accurately describe the interface's scope: replace "EmbeddingModel interface for
embedding models" with a concise description mentioning that ModelDriver is an
interface for model drivers (chat, embedding, rerank, listing), plus balance and
connection-checking operations; ensure the comment sits immediately above the
type ModelDriver declaration so readers see the updated responsibility summary.

In `@internal/service/chunk.go`:
- Around line 371-381: The else-if branch declares a new local "var err error"
which shadows the outer err; remove that declaration and use existing err (i.e.,
use "=" assignments for the calls to dao.LookupTenantLLMByName and
s.modelProvider.GetRerankModel) so the error variable is consistent with the
first branch and avoids accidental shadowing around req.RerankID handling.

In `@internal/service/model_service.go`:
- Around line 70-117: The GetEmbeddingModel/ChatModel/GetRerankModel blocks
duplicate ~50 lines (parseModelName → TenantLLM lookup → resolve apiBase →
entity.NewProviderManager → CreateModelDriver) and re-read conf/models per
request; extract this into a single helper on ModelProviderImpl (e.g.,
buildDriver or resolveDriver) and memoize the ProviderManager via a
package-level getProviderManager using sync.Once (as sketched). Replace the
duplicated sequences in GetEmbeddingModel (and the analogous methods at ~120-167
and ~170-216) to call the new helper; the helper should call parseModelName,
dao.NewTenantLLMDAO().GetByTenantFactoryAndModelName, validate APIKey, resolve
apiBase using dao.NewModelProviderDAO() fallback, obtain the cached
ProviderManager (entity.NewProviderManager via getProviderManager), find
providerEntity, and invoke modelModule.NewModelFactory().CreateModelDriver,
returning (modelModule.ModelDriver, *modelModule.APIConfig, error).
🪄 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: cddde8db-71ac-4acc-9299-06bdfbd4fcd0

📥 Commits

Reviewing files that changed from the base of the PR and between 61a24a2 and 6ed97f2.

📒 Files selected for processing (26)
  • conf/models/zhipu-ai.json
  • internal/entity/model.go
  • internal/entity/models/aliyun.go
  • internal/entity/models/deepseek.go
  • internal/entity/models/dummy.go
  • internal/entity/models/factory.go
  • internal/entity/models/gitee.go
  • internal/entity/models/minimax.go
  • internal/entity/models/moonshot.go
  • internal/entity/models/siliconflow.go
  • internal/entity/models/types.go
  • internal/entity/models/zhipu-ai.go
  • internal/entity/types.go
  • internal/service/chunk.go
  • internal/service/model_bundle.go
  • internal/service/model_service.go
  • internal/service/models/deepseek_model.go
  • internal/service/models/factory.go
  • internal/service/models/gitee_model.go
  • internal/service/models/moonshot_model.go
  • internal/service/models/openai_api_compatible_model.go
  • internal/service/models/openai_model.go
  • internal/service/models/siliconflow_model.go
  • internal/service/models/zhipu_model.go
  • internal/service/nlp/reranker.go
  • internal/service/nlp/retrieval.go
💤 Files with no reviewable changes (8)
  • internal/service/models/moonshot_model.go
  • internal/service/models/deepseek_model.go
  • internal/service/models/gitee_model.go
  • internal/service/models/siliconflow_model.go
  • internal/service/models/zhipu_model.go
  • internal/service/models/openai_api_compatible_model.go
  • internal/service/models/openai_model.go
  • internal/service/models/factory.go

Comment thread internal/entity/model.go Outdated
Comment on lines 274 to 277
provider.ModelDriver, err = modelFactory.CreateModelDriver(provider.Name, provider.URL, provider.URLSuffix, "")
if err != nil {
return nil, fmt.Errorf("error creating model driver for provider %s: %w", provider.Name, 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.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Find all read-side usages of Provider.ModelDriver to see whether it is invoked directly.
rg -nP '\bModelDriver\b' --type=go -g '!**/vendor/**' -C2
echo '---'
# Specifically, look for usages on a Provider value (e.g., `.ModelDriver.` or `provider.ModelDriver`).
rg -nP '\.ModelDriver\.' --type=go -g '!**/vendor/**' -C2

Repository: infiniflow/ragflow

Length of output: 14616


🏁 Script executed:

# Check ZhipuAIModel Chat implementations
rg -n 'func.*Chat' internal/entity/models/zhipu-ai.go -A 20

Repository: infiniflow/ragflow

Length of output: 2168


🏁 Script executed:

# Check SiliconflowModel Chat implementations
rg -n 'func.*Chat' internal/entity/models/siliconflow.go -A 20

Repository: infiniflow/ragflow

Length of output: 2076


🏁 Script executed:

# Also check EncodeQuery and EncodeToEmbedding for both providers
rg -n 'func.*Encode' internal/entity/models/zhipu-ai.go -A 15
rg -n 'func.*Encode' internal/entity/models/siliconflow.go -A 15

Repository: infiniflow/ragflow

Length of output: 2857


🏁 Script executed:

# Check struct definitions and any ModelName field
rg -n 'type ZhipuAIModel struct' internal/entity/models/zhipu-ai.go -A 10
rg -n 'type SiliconflowModel struct' internal/entity/models/siliconflow.go -A 10

Repository: infiniflow/ragflow

Length of output: 903


🏁 Script executed:

# Check if z.ModelName is ever referenced
rg 'z\.ModelName|s\.ModelName' internal/entity/models/zhipu-ai.go internal/entity/models/siliconflow.go

Repository: infiniflow/ragflow

Length of output: 242


🏁 Script executed:

# See full ChatWithMessages implementation for ZhipuAI
sed -n '191,220p' internal/entity/models/zhipu-ai.go

Repository: infiniflow/ragflow

Length of output: 910


🏁 Script executed:

# Find exact line numbers for z.ModelName usage in zhipu-ai.go
grep -n 'z\.ModelName' internal/entity/models/zhipu-ai.go

Repository: infiniflow/ragflow

Length of output: 91


🏁 Script executed:

# Find exact line numbers for s.ModelName usage in siliconflow.go
grep -n 's\.ModelName' internal/entity/models/siliconflow.go

Repository: infiniflow/ragflow

Length of output: 114


🏁 Script executed:

# Get context around these usages
rg -n '"model": z\.ModelName' internal/entity/models/zhipu-ai.go -B 5 -A 5
rg -n 'model := s\.ModelName' internal/entity/models/siliconflow.go -B 5 -A 5

Repository: infiniflow/ragflow

Length of output: 597


Fix empty modelName for provider-level driver: breaks Zhipu-AI and Siliconflow operations.

CreateModelDriver now wires the modelName argument into NewZhipuAIModel(...) and NewSiliconflowModel(...), storing it as a struct field used in API requests. Constructing the provider-level driver with "" means ZhipuAIModel.ModelName and SiliconflowModel.ModelName are both empty strings.

This breaks multiple code paths in model_service.go that call provider-level driver methods directly:

  • Balance() (line 568): uses s.ModelName struct field
  • CheckConnection() (line 620): uses s.ModelName struct field
  • EncodeToEmbedding() (called via embedding flow): uses struct field

These will all send empty "model" values to the API. Pass an actual model name at provider construction time, or refactor to create drivers per-request with the correct model name.

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

In `@internal/entity/model.go` around lines 274 - 277, The provider-level driver
is being created with an empty modelName (CreateModelDriver(..., "")) which
leaves ZhipuAIModel.ModelName and SiliconflowModel.ModelName empty and breaks
calls like Balance(), CheckConnection(), and EncodeToEmbedding; fix by passing
the provider's configured default model name when constructing the provider
driver (e.g. use provider.DefaultModel or provider.ModelName — whichever field
holds the provider's default model) instead of "", or change CreateModelDriver
usage to construct drivers per-request with the correct model name so
NewZhipuAIModel and NewSiliconflowModel receive the actual modelName.

Comment thread internal/entity/models/aliyun.go Resolved
Comment on lines +76 to +84
// Encode encodes a list of texts into embeddings (convenience method)
func (z *MoonshotModel) Encode(texts []string, apiConfig *APIConfig) ([][]float64, error) {
return nil, fmt.Errorf("%s, Encode not implemented", z.Name())
}

// EncodeQuery encodes a single query string into embedding (convenience method)
func (z *MoonshotModel) EncodeQuery(query string, apiConfig *APIConfig) ([]float64, error) {
return nil, fmt.Errorf("%s, EncodeQuery not implemented", z.Name())
}

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 | 🟡 Minor

Track follow-up: Moonshot embedding/rerank still stubbed.

Encode, EncodeQuery, and Rerank only return “not implemented” errors. Since Moonshot is a real provider, any caller selecting Moonshot for embedding or rerank in the new pipeline will fail at runtime. Confirm this is deferred work and tracked, or wire up the real HTTP path before this is callable through the retrieval/reranker flow.

Want me to open a tracking issue for the missing Moonshot embedding/rerank implementations?

Also applies to: 206-210

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

In `@internal/entity/models/moonshot.go` around lines 76 - 84, The Moonshot
embedding/rerank methods Encode, EncodeQuery, and Rerank on MoonshotModel are
only stubs and will cause runtime failures; fix by either (A) implementing the
real HTTP calls: use APIConfig in MoonshotModel.Encode and EncodeQuery to POST
to Moonshot's embedding endpoint, parse and return [][]float64 / []float64 with
proper error handling and timeouts, and implement MoonshotModel.Rerank to call
the rerank endpoint and map scores back to the expected signature, or (B) if
deferring, gate Moonshot selection in the retrieval/reranker flow and replace
these stubs with explicit "feature disabled" errors plus a reference to a
tracking issue ID and a TODO comment so callers cannot select Moonshot; update
any selection logic that references MoonshotModel to respect the gate.

Comment thread internal/entity/models/siliconflow.go Outdated
Comment on lines +470 to +478
func (s *SiliconflowModel) EncodeQuery(query string, apiConfig *APIConfig) ([]float64, error) {
embeddings, err := s.Encode([]string{query}, apiConfig)
if err != nil {
return nil, err
}
if len(embeddings) == 0 {
return nil, fmt.Errorf("no embedding returned")
}
return embeddings[0], 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.

⚠️ Potential issue | 🟡 Minor

EncodeQuery can return a nil vector on a malformed response.

embeddings is sized via make([][]float64, len(texts)), so for a single-item batch len(embeddings) is always 1 even if the upstream response contained no data entry for index 0 — embeddings[0] would then be nil and silently returned. Downstream code (e.g. RetrievalService.GetVector → MatchDenseExpr.EmbeddingData) will accept it but produce a degenerate query vector.

🛡️ Suggested guard
 	embeddings, err := s.Encode([]string{query}, apiConfig)
 	if err != nil {
 		return nil, err
 	}
-	if len(embeddings) == 0 {
-		return nil, fmt.Errorf("no embedding returned")
+	if len(embeddings) == 0 || embeddings[0] == nil {
+		return nil, fmt.Errorf("no embedding returned")
 	}
 	return embeddings[0], nil
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/entity/models/siliconflow.go` around lines 470 - 478, The
EncodeQuery method may return a nil slice when the upstream embedding response
lacked data for index 0; update SiliconflowModel.EncodeQuery to validate that
embeddings is non-nil, has length > 0, and that embeddings[0] is non-nil/has
non-zero length before returning it, and return a descriptive error (e.g. "no
embedding returned for query") if the guard fails; use the existing Encode call
and the embeddings variable to locate the check and error path.

Comment on lines +605 to +611

body, _ := io.ReadAll(resp.Body)

var rerankResp SiliconflowRerankResponse
if err := json.Unmarshal(body, &rerankResp); err != nil {
return nil, fmt.Errorf("failed to decode response: %w", 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.

⚠️ Potential issue | 🟡 Minor

Discarded io.ReadAll error obscures transport failures.

If the body read fails (truncated response, transport reset after status was received, etc.), body will be empty and the subsequent json.Unmarshal will surface an unexpected end of JSON input error rather than the actual I/O cause, making this hard to diagnose in production. Either propagate the read error, or switch to streaming decode like EncodeToEmbedding does on line 450.

🛠️ Suggested fix
-	body, _ := io.ReadAll(resp.Body)
-
-	var rerankResp SiliconflowRerankResponse
-	if err := json.Unmarshal(body, &rerankResp); err != nil {
-		return nil, fmt.Errorf("failed to decode response: %w", err)
-	}
+	var rerankResp SiliconflowRerankResponse
+	if err := json.NewDecoder(resp.Body).Decode(&rerankResp); err != nil {
+		return nil, fmt.Errorf("failed to decode response: %w", err)
+	}
📝 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
body, _ := io.ReadAll(resp.Body)
var rerankResp SiliconflowRerankResponse
if err := json.Unmarshal(body, &rerankResp); err != nil {
return nil, fmt.Errorf("failed to decode response: %w", err)
}
var rerankResp SiliconflowRerankResponse
if err := json.NewDecoder(resp.Body).Decode(&rerankResp); err != nil {
return nil, fmt.Errorf("failed to decode response: %w", err)
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/entity/models/siliconflow.go` around lines 605 - 611, The code
currently ignores the error from io.ReadAll(resp.Body) causing transport/read
failures to be masked by json.Unmarshal; update the block around
io.ReadAll(resp.Body) to handle and return the read error (or use
json.NewDecoder(resp.Body).Decode(&rerankResp) as EncodeToEmbedding does) so
that failures surface correctly; specifically, check the error returned by
io.ReadAll (or replace with streaming json.Decoder) before calling
json.Unmarshal on SiliconflowRerankResponse.

Comment thread internal/entity/models/types.go Resolved
Comment thread internal/entity/types.go Resolved
Comment thread internal/service/model_service.go Resolved
@qinling0210
qinling0210 force-pushed the refactor_go_model branch 2 times, most recently from 4150ba9 to 95775b0 Compare April 27, 2026 12:37
}

// EmbeddingModel wraps a ModelDriver with embedding-specific configuration
type EmbeddingModel struct {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

type EmbeddingModel struct {
ModelDriver *ModelDriver
ModelName *string
APIConfig *APIConfig
}

}

// RerankModel wraps a ModelDriver with rerank-specific configuration
type RerankModel struct {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

type RerankModel struct {
ModelDriver *ModelDriver
ModelName *string
APIConfig *APIConfig
}

Comment on lines +110 to +131
type RerankModel struct {
ModelDriver ModelDriver
ModelName string
APIConfig *APIConfig
}

// NewRerankModel creates a new RerankModel
func NewRerankModel(driver ModelDriver, modelName string, apiConfig *APIConfig) *RerankModel {
return &RerankModel{
ModelDriver: driver,
ModelName: modelName,
APIConfig: apiConfig,
}
}

// Rerank calculates similarity between query and texts
func (r *RerankModel) Rerank(query string, texts []string, apiConfig *APIConfig) ([]float64, error) {
return r.ModelDriver.Rerank(&r.ModelName, query, texts, apiConfig)
}

// ChatModel wraps a ModelDriver with chat-specific configuration
type ChatModel struct {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

type ChatModel struct {
ModelDriver *ModelDriver
ModelName *string
APIConfig *APIConfig
}

@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: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/entity/models/aliyun.go (1)

55-57: ⚠️ Potential issue | 🔴 Critical

Critical: AliyunModel.Name() returns "siliconflow" instead of "aliyun" (copy-paste bug).

This is a load-bearing bug because the new Encode/EncodeQuery/Rerank stubs (lines 342, 347, 352) and existing methods at lines 188, 337, 427 all embed z.Name() in their error messages. Every error from an Aliyun provider will be incorrectly reported as a SiliconFlow error, which will severely mislead operators triaging failures and corrupt any caller that branches on driver name.

Fix by changing line 56 to return "aliyun":

Proposed fix
 func (z *AliyunModel) Name() string {
-	return "siliconflow"
+	return "aliyun"
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/entity/models/aliyun.go` around lines 55 - 57, AliyunModel.Name()
currently returns the wrong literal ("siliconflow") due to a copy/paste error;
update the Name() method (AliyunModel.Name) to return "aliyun" so that all error
messages and callers using z.Name() correctly identify the provider; locate the
Name() function on type AliyunModel and replace the returned string with
"aliyun".
♻️ Duplicate comments (3)
internal/entity/models/siliconflow.go (2)

621-626: ⚠️ Potential issue | 🟡 Minor

Discarded io.ReadAll error still obscures transport failures.

body, _ := io.ReadAll(resp.Body) on the success path swallows truncated-response / connection-reset errors, so the subsequent json.Unmarshal surfaces a misleading unexpected end of JSON input instead of the real I/O cause. Either propagate the read error or switch to a streaming decoder.

🛠️ Suggested fix
-	body, _ := io.ReadAll(resp.Body)
-
-	var rerankResp SiliconflowRerankResponse
-	if err := json.Unmarshal(body, &rerankResp); err != nil {
-		return nil, fmt.Errorf("failed to decode response: %w", err)
-	}
+	var rerankResp SiliconflowRerankResponse
+	if err := json.NewDecoder(resp.Body).Decode(&rerankResp); err != nil {
+		return nil, fmt.Errorf("failed to decode response: %w", err)
+	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/entity/models/siliconflow.go` around lines 621 - 626, The code
currently discards the io.ReadAll error which can hide transport/truncation
failures before json.Unmarshal on SiliconflowRerankResponse, so change the
read-and-decode logic in the function containing the resp handling to propagate
the read error (e.g., check and return fmt.Errorf when io.ReadAll(resp.Body)
returns an error) or replace with a streaming json.Decoder
(json.NewDecoder(resp.Body).Decode(&rerankResp)) to avoid swallowing I/O errors
and ensure the caller receives the real transport error instead of an
"unexpected end of JSON input".

487-495: ⚠️ Potential issue | 🟡 Minor

EncodeQuery can return a nil slice on a malformed upstream response.

embeddings is sized via make([][]float64, len(texts)), so for the single-element batch in EncodeQuery, len(embeddings) is always 1 — the len(embeddings) == 0 guard at line 492 cannot fire even if the response contained no entry for index 0. embeddings[0] would be nil and silently propagate to MatchDenseExpr.EmbeddingData in RetrievalService.GetVector, producing a degenerate query vector.

🛡️ Suggested guard
-	if len(embeddings) == 0 {
-		return nil, fmt.Errorf("no embedding returned")
-	}
-	return embeddings[0], nil
+	if len(embeddings) == 0 || len(embeddings[0]) == 0 {
+		return nil, fmt.Errorf("no embedding returned")
+	}
+	return embeddings[0], nil
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/entity/models/siliconflow.go` around lines 487 - 495, EncodeQuery
currently assumes embeddings[0] is non-nil even when the upstream response is
malformed; update SiliconflowModel.EncodeQuery to validate the returned
embeddings slice and the first element before returning: after calling s.Encode,
check that embeddings is non-nil, has length >= 1, that embeddings[0] is non-nil
and has non-zero length, and return a descriptive error if any of those checks
fail so a nil/empty embedding is never propagated (this change touches
SiliconflowModel.EncodeQuery and guards the downstream use in
RetrievalService.GetVector / MatchDenseExpr.EmbeddingData).
internal/service/model_service.go (1)

888-913: ⚠️ Potential issue | 🔴 Critical

Persisting: discarded NewProviderManager error → nil-pointer panic; tenant apiBase silently dropped.

The same two bugs flagged on the previous revision are still present:

  1. Line 903 drops the error from entity.NewProviderManager("conf/models") via _. If the call fails, providerManager is nil and providerManager.FindProvider(...) on line 904 panics.
  2. Lines 888–898 carefully resolve apiBase from tenantLLM.APIBase (with fallback to providerDAO.GetProviderByName(provider).DefaultURL) and build baseURLMap from it on line 901, but line 908 unconditionally overwrites it with providerEntity.URL. The tenant-level API base override is silently discarded, the error path at line 895 covers a value that is never used, and lines 888–901 become dead code.
🛠️ Proposed fix
-	factory := modelModule.NewModelFactory()
-	baseURLMap := map[string]string{"default": apiBase}
-
-	providerManager, _ := entity.NewProviderManager("conf/models")
-	providerEntity := providerManager.FindProvider(strings.ToLower(provider))
-	if providerEntity == nil {
-		return nil, "", nil, fmt.Errorf("provider %s not found in conf/models", provider)
-	}
-	baseURLMap = providerEntity.URL
-	urlSuffix := providerEntity.URLSuffix
-	modelDriver, err := factory.CreateModelDriver(provider, baseURLMap, urlSuffix)
+	providerManager, err := entity.NewProviderManager("conf/models")
+	if err != nil || providerManager == nil {
+		return nil, "", nil, fmt.Errorf("failed to load provider manager: %w", err)
+	}
+	providerEntity := providerManager.FindProvider(strings.ToLower(provider))
+	if providerEntity == nil {
+		return nil, "", nil, fmt.Errorf("provider %s not found in conf/models", provider)
+	}
+	baseURLMap := providerEntity.URL
+	if apiBase != "" {
+		baseURLMap = map[string]string{"default": apiBase}
+	}
+	urlSuffix := providerEntity.URLSuffix
+	factory := modelModule.NewModelFactory()
+	modelDriver, err := factory.CreateModelDriver(provider, baseURLMap, urlSuffix)

If tenant overrides are intentionally not supported, delete lines 888–901 instead so the dead computation does not mislead readers.

🤖 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 888 - 913, Handle both the
nil-pointer and tenant-override bugs: stop discarding the error from
entity.NewProviderManager("conf/models")—capture its error, return it (or handle
it) if non-nil instead of using `_`, and only call
providerManager.FindProvider(...) when providerManager is valid; and preserve
tenant APIBase by building baseURLMap so tenantLLM.APIBase (and the providerDAO
fallback) win when set, otherwise fall back to providerEntity.URL (do not
unconditionally overwrite baseURLMap with providerEntity.URL); update the code
around NewProviderManager, providerManager.FindProvider, tenantLLM.APIBase,
providerDAO.GetProviderByName and baseURLMap to implement these checks and merge
logic (or remove the tenant-override code if tenant overrides are intentionally
unsupported).
🧹 Nitpick comments (3)
internal/service/chunk.go (1)

216-216: Optional: hoist NewModelProviderService to a single instance.

NewModelProviderService() is constructed up to three times in RetrievalTest (Lines 216, 267, 342) — each instantiation re-creates all DAOs. Consider lifting it to a single local variable near the top of the method (or a ChunkService field) so all branches reuse it.

Also applies to: 267-267, 342-342

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

In `@internal/service/chunk.go` at line 216, RetrievalTest currently calls
NewModelProviderService() multiple times (e.g., the local instantiation at the
line with modelProviderSvc := NewModelProviderService() and the other calls at
the RetrievalTest branches), which recreates DAOs unnecessarily; hoist a single
NewModelProviderService() call to the top of RetrievalTest (or make it a
ChunkService field) and reuse that single modelProviderSvc in all branches
(replace the repeated NewModelProviderService() calls in RetrievalTest and any
branch code with the hoisted modelProviderSvc) so DAOs are created once.
internal/entity/models/deepseek.go (1)

489-493: Optional: co-locate Rerank with Encode/EncodeQuery.

Rerank is appended at the bottom of the file (Lines 490–493) while Encode/EncodeQuery are placed near EncodeToEmbedding (Lines 404–412). For readability, group all three new convenience methods together as is done in the other model files (gitee.go, aliyun.go, dummy.go).

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

In `@internal/entity/models/deepseek.go` around lines 489 - 493, The Rerank method
is placed far from the related convenience methods; move the Rerank(func (z
*DeepSeekModel) Rerank(...)) implementation so it sits alongside Encode,
EncodeQuery and EncodeToEmbedding (i.e., group all three convenience methods
together in the DeepSeekModel block), preserving the exact signature and
receiver, any comment header ("Rerank calculates..."), and return behavior so
the file remains compilable and consistent with other model files.
internal/entity/models/siliconflow.go (1)

600-600: Use bytes.NewReader instead of strings.NewReader(string(jsonData)).

jsonData is already []byte; converting to string and back to a reader allocates an extra copy. bytes.NewReader(jsonData) (or bytes.NewBuffer(jsonData), matching what Chat/ChatStreamlyWithSender already use in this file) is both cheaper and idiomatic.

-	req, err := http.NewRequest("POST", url, strings.NewReader(string(jsonData)))
+	req, err := http.NewRequest("POST", url, bytes.NewReader(jsonData))
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/entity/models/siliconflow.go` at line 600, The http.NewRequest call
currently wraps jsonData with strings.NewReader(string(jsonData)), causing an
extra allocation; change that to use bytes.NewReader(jsonData) (or
bytes.NewBuffer(jsonData)) where jsonData is used, replacing
strings.NewReader(string(jsonData)) in the http.NewRequest(...) invocation so
the request body is constructed from the original []byte without converting to
string.
🤖 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/models/siliconflow.go`:
- Around line 568-591: The Rerank method dereferences modelName without a nil
check which can panic; in SiliconflowModel.Rerank add a defensive guard before
building SiliconflowRerankRequest so that if modelName is nil you either (a) set
modelName to the same default/model-from-apiConfig value used by the embedding
path or (b) return a clear error instead of dereferencing nil; ensure you update
the assignment that sets SiliconflowRerankRequest.Model (currently using
*modelName) to use the guarded value or the error path.
- Around line 386-479: In EncodeToEmbedding, stop issuing one HTTP request per
text and instead send a single POST with the full texts slice as the "input"
field (i.e., build reqBody with "model": <only if modelName is
non-nil/non-empty>, "input": texts) so the SiliconFlow batch embedding API is
used; also guard against a nil modelName by either returning an error or
omitting the "model" key when modelName == nil or empty (validate in
EncodeToEmbedding before marshaling), then parse the response's data array into
embeddings one-to-one with texts and populate embeddings[i] accordingly (adjust
handling of result["data"] and embedding extraction to expect one embedding per
input).

In `@internal/entity/models/types.go`:
- Around line 92-128: The wrapper types are inconsistent: make the wrappers own
state (Option A) by changing EmbeddingModel.Encode and EncodeQuery to use
e.ModelName and e.APIConfig (drop the modelName/apiConfig params) and change
RerankModel.Rerank to use r.ModelName and r.APIConfig (drop the apiConfig
param), then update all call sites (e.g. RetrievalService.GetVector and
RerankByModel and any places currently calling
ModelDriver.Encode/EncodeQuery/Rerank directly) to call
embModel.Encode/EncodeQuery and rerankModel.Rerank on the wrapper instances
instead of dereferencing ModelDriver and passing ModelName/APIConfig manually;
ensure signatures and any interface implementations (ModelDriver usage) are
adjusted to match the new wrapper-owned-params shape.

In `@internal/service/model_bundle.go`:
- Around line 33-43: The ModelBundle constructor sets bundle.embeddingConfig but
no code reads it; either remove the unused field or thread it into the encoding
paths: update NewModelBundle (and the ModelBundle struct) to stop initializing
embeddingConfig if you choose removal, or propagate embeddingConfig into Encode
and EncodeQuery by replacing b.apiConfig usage (or adding an extra param) so
Encode/EncodeQuery use b.embeddingConfig for batch size/dimensions; adjust call
sites accordingly (look for NewModelBundle, ModelBundle.embeddingConfig, Encode,
EncodeQuery, and b.apiConfig) to keep the code consistent.

---

Outside diff comments:
In `@internal/entity/models/aliyun.go`:
- Around line 55-57: AliyunModel.Name() currently returns the wrong literal
("siliconflow") due to a copy/paste error; update the Name() method
(AliyunModel.Name) to return "aliyun" so that all error messages and callers
using z.Name() correctly identify the provider; locate the Name() function on
type AliyunModel and replace the returned string with "aliyun".

---

Duplicate comments:
In `@internal/entity/models/siliconflow.go`:
- Around line 621-626: The code currently discards the io.ReadAll error which
can hide transport/truncation failures before json.Unmarshal on
SiliconflowRerankResponse, so change the read-and-decode logic in the function
containing the resp handling to propagate the read error (e.g., check and return
fmt.Errorf when io.ReadAll(resp.Body) returns an error) or replace with a
streaming json.Decoder (json.NewDecoder(resp.Body).Decode(&rerankResp)) to avoid
swallowing I/O errors and ensure the caller receives the real transport error
instead of an "unexpected end of JSON input".
- Around line 487-495: EncodeQuery currently assumes embeddings[0] is non-nil
even when the upstream response is malformed; update
SiliconflowModel.EncodeQuery to validate the returned embeddings slice and the
first element before returning: after calling s.Encode, check that embeddings is
non-nil, has length >= 1, that embeddings[0] is non-nil and has non-zero length,
and return a descriptive error if any of those checks fail so a nil/empty
embedding is never propagated (this change touches SiliconflowModel.EncodeQuery
and guards the downstream use in RetrievalService.GetVector /
MatchDenseExpr.EmbeddingData).

In `@internal/service/model_service.go`:
- Around line 888-913: Handle both the nil-pointer and tenant-override bugs:
stop discarding the error from entity.NewProviderManager("conf/models")—capture
its error, return it (or handle it) if non-nil instead of using `_`, and only
call providerManager.FindProvider(...) when providerManager is valid; and
preserve tenant APIBase by building baseURLMap so tenantLLM.APIBase (and the
providerDAO fallback) win when set, otherwise fall back to providerEntity.URL
(do not unconditionally overwrite baseURLMap with providerEntity.URL); update
the code around NewProviderManager, providerManager.FindProvider,
tenantLLM.APIBase, providerDAO.GetProviderByName and baseURLMap to implement
these checks and merge logic (or remove the tenant-override code if tenant
overrides are intentionally unsupported).

---

Nitpick comments:
In `@internal/entity/models/deepseek.go`:
- Around line 489-493: The Rerank method is placed far from the related
convenience methods; move the Rerank(func (z *DeepSeekModel) Rerank(...))
implementation so it sits alongside Encode, EncodeQuery and EncodeToEmbedding
(i.e., group all three convenience methods together in the DeepSeekModel block),
preserving the exact signature and receiver, any comment header ("Rerank
calculates..."), and return behavior so the file remains compilable and
consistent with other model files.

In `@internal/entity/models/siliconflow.go`:
- Line 600: The http.NewRequest call currently wraps jsonData with
strings.NewReader(string(jsonData)), causing an extra allocation; change that to
use bytes.NewReader(jsonData) (or bytes.NewBuffer(jsonData)) where jsonData is
used, replacing strings.NewReader(string(jsonData)) in the http.NewRequest(...)
invocation so the request body is constructed from the original []byte without
converting to string.

In `@internal/service/chunk.go`:
- Line 216: RetrievalTest currently calls NewModelProviderService() multiple
times (e.g., the local instantiation at the line with modelProviderSvc :=
NewModelProviderService() and the other calls at the RetrievalTest branches),
which recreates DAOs unnecessarily; hoist a single NewModelProviderService()
call to the top of RetrievalTest (or make it a ChunkService field) and reuse
that single modelProviderSvc in all branches (replace the repeated
NewModelProviderService() calls in RetrievalTest and any branch code with the
hoisted modelProviderSvc) so DAOs are created once.
🪄 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: 232e3a8d-2c86-4fac-ae2e-d0f093d0ad6d

📥 Commits

Reviewing files that changed from the base of the PR and between 6ed97f2 and 6437116.

📒 Files selected for processing (25)
  • conf/models/zhipu-ai.json
  • internal/entity/models/aliyun.go
  • internal/entity/models/deepseek.go
  • internal/entity/models/dummy.go
  • internal/entity/models/gitee.go
  • internal/entity/models/google.go
  • internal/entity/models/minimax.go
  • internal/entity/models/moonshot.go
  • internal/entity/models/siliconflow.go
  • internal/entity/models/types.go
  • internal/entity/models/zhipu-ai.go
  • internal/entity/types.go
  • internal/service/chunk.go
  • internal/service/model_bundle.go
  • internal/service/model_service.go
  • internal/service/models/deepseek_model.go
  • internal/service/models/factory.go
  • internal/service/models/gitee_model.go
  • internal/service/models/moonshot_model.go
  • internal/service/models/openai_api_compatible_model.go
  • internal/service/models/openai_model.go
  • internal/service/models/siliconflow_model.go
  • internal/service/models/zhipu_model.go
  • internal/service/nlp/reranker.go
  • internal/service/nlp/retrieval.go
💤 Files with no reviewable changes (8)
  • internal/service/models/moonshot_model.go
  • internal/service/models/zhipu_model.go
  • internal/service/models/siliconflow_model.go
  • internal/service/models/openai_model.go
  • internal/service/models/openai_api_compatible_model.go
  • internal/service/models/gitee_model.go
  • internal/service/models/deepseek_model.go
  • internal/service/models/factory.go
✅ Files skipped from review due to trivial changes (1)
  • conf/models/zhipu-ai.json
🚧 Files skipped from review as they are similar to previous changes (4)
  • internal/entity/models/minimax.go
  • internal/entity/models/moonshot.go
  • internal/entity/models/zhipu-ai.go
  • internal/service/nlp/reranker.go

Comment on lines +386 to +479
func (s *SiliconflowModel) EncodeToEmbedding(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([][]float64, error) {
if len(texts) == 0 {
return [][]float64{}, nil
}

var region = "default"
if apiConfig != nil && apiConfig.Region != nil {
region = *apiConfig.Region
}

url := fmt.Sprintf("%s/%s", strings.TrimSuffix(s.BaseURL[region], "/"), s.URLSuffix.Embedding)

apiKey := ""
if apiConfig != nil && apiConfig.ApiKey != nil {
apiKey = *apiConfig.ApiKey
}

embeddings := make([][]float64, len(texts))

for i, text := range texts {
reqBody := map[string]interface{}{
"model": modelName,
"input": text,
}

jsonData, err := json.Marshal(reqBody)
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}

req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}

req.Header.Set("Content-Type", "application/json")
if apiKey != "" {
req.Header.Set("Authorization", "Bearer "+apiKey)
}

resp, err := s.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to send request: %w", err)
}

body, err := io.ReadAll(resp.Body)
resp.Body.Close()

if err != nil {
return nil, fmt.Errorf("failed to read response: %w", err)
}

if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("SILICONFLOW API error: %s, body: %s", resp.Status, string(body))
}

// Parse response
var result map[string]interface{}
if err = json.Unmarshal(body, &result); err != nil {
return nil, fmt.Errorf("failed to parse response: %w", err)
}

data, ok := result["data"].([]interface{})
if !ok || len(data) == 0 {
return nil, fmt.Errorf("no data in response")
}

firstData, ok := data[0].(map[string]interface{})
if !ok {
return nil, fmt.Errorf("invalid data format")
}

embeddingSlice, ok := firstData["embedding"].([]interface{})
if !ok {
return nil, fmt.Errorf("invalid embedding format")
}

embedding := make([]float64, len(embeddingSlice))
for j, v := range embeddingSlice {
switch val := v.(type) {
case float64:
embedding[j] = val
case float32:
embedding[j] = float64(val)
default:
return nil, fmt.Errorf("unexpected embedding value type")
}
}

embeddings[i] = embedding
}

return embeddings, 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.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🌐 Web query:

SiliconFlow embeddings API batch input array support

💡 Result:

Yes, the SiliconFlow embeddings API supports batch input via an array in the "input" field of a single /v1/embeddings request. The input can be a string or an array of strings (up to 32 items maximum, each up to 512 tokens). The response returns a list of embeddings corresponding to each input item. There is also a separate batch API for file-based async processing of larger volumes, but the standard embeddings endpoint natively handles array batching.

Citations:


Major: per-text HTTP loop regresses batched embedding performance and silently fails on nil modelName.

Two issues in EncodeToEmbedding:

  1. Batching lost. The implementation issues one HTTP request per text (for i, text := range texts { ... POST ... }), whereas the SiliconFlow embedding API accepts "input": [...] for batch encoding in a single request. For knowledge base ingestion embedding thousands of chunks, this converts a few batch round-trips into thousands of individual requests on a 120s-timeout client — a significant latency and rate-limit regression that impacts production indexing pipelines.

  2. modelName nil not handled. Line 407 marshals the raw *string into map[string]interface{}. If a caller passes nil (valid per the signature), the request body becomes "model": null, which the API rejects. Add a nil/empty check or require non-nil at the boundary.

🛠️ Suggested fix (restore batching + handle nil model)
func (s *SiliconflowModel) EncodeToEmbedding(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([][]float64, error) {
	if len(texts) == 0 {
		return [][]float64{}, nil
	}
+	if modelName == nil || *modelName == "" {
+		return nil, fmt.Errorf("modelName is required")
+	}

	var region = "default"
	if apiConfig != nil && apiConfig.Region != nil {
		region = *apiConfig.Region
	}

	url := fmt.Sprintf("%s/%s", strings.TrimSuffix(s.BaseURL[region], "/"), s.URLSuffix.Embedding)

	apiKey := ""
	if apiConfig != nil && apiConfig.ApiKey != nil {
		apiKey = *apiConfig.ApiKey
	}

-	embeddings := make([][]float64, len(texts))
-
-	for i, text := range texts {
 		reqBody := map[string]interface{}{
-			"model": modelName,
-			"input": text,
+			"model": *modelName,
+			"input": texts,
 		}
-		// ... per-text request loop ...
-	}
+	// single batch request, then parse response data array into embeddings by index
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/entity/models/siliconflow.go` around lines 386 - 479, In
EncodeToEmbedding, stop issuing one HTTP request per text and instead send a
single POST with the full texts slice as the "input" field (i.e., build reqBody
with "model": <only if modelName is non-nil/non-empty>, "input": texts) so the
SiliconFlow batch embedding API is used; also guard against a nil modelName by
either returning an error or omitting the "model" key when modelName == nil or
empty (validate in EncodeToEmbedding before marshaling), then parse the
response's data array into embeddings one-to-one with texts and populate
embeddings[i] accordingly (adjust handling of result["data"] and embedding
extraction to expect one embedding per input).

Comment on lines +568 to +591
func (s *SiliconflowModel) Rerank(modelName *string, query string, texts []string, apiConfig *APIConfig) ([]float64, error) {
if len(texts) == 0 {
return []float64{}, nil
}

var region = "default"
if apiConfig != nil && apiConfig.Region != nil {
region = *apiConfig.Region
}

apiKey := ""
if apiConfig != nil && apiConfig.ApiKey != nil {
apiKey = *apiConfig.ApiKey
}

reqBody := SiliconflowRerankRequest{
Model: *modelName,
Query: query,
Documents: texts,
TopN: len(texts),
ReturnDocuments: false,
MaxChunksPerDoc: 1024,
OverlapTokens: 80,
}

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

Rerank dereferences modelName without a nil check.

Line 584 does Model: *modelName. The interface signature accepts modelName *string, so a nil argument is reachable and will panic before the request is built. Add a defensive guard mirroring the embedding path, or document a non-nil precondition in the interface.

🛡️ Suggested guard
 func (s *SiliconflowModel) Rerank(modelName *string, query string, texts []string, apiConfig *APIConfig) ([]float64, error) {
 	if len(texts) == 0 {
 		return []float64{}, nil
 	}
+	if modelName == nil || *modelName == "" {
+		return nil, fmt.Errorf("modelName is required")
+	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/entity/models/siliconflow.go` around lines 568 - 591, The Rerank
method dereferences modelName without a nil check which can panic; in
SiliconflowModel.Rerank add a defensive guard before building
SiliconflowRerankRequest so that if modelName is nil you either (a) set
modelName to the same default/model-from-apiConfig value used by the embedding
path or (b) return a clear error instead of dereferencing nil; ensure you update
the assignment that sets SiliconflowRerankRequest.Model (currently using
*modelName) to use the guarded value or the error path.

Comment on lines +92 to +128
// Encode encodes a list of texts into embeddings
func (e *EmbeddingModel) Encode(modelName *string, texts []string, apiConfig *APIConfig) ([][]float64, error) {
return e.ModelDriver.EncodeToEmbedding(modelName, texts, apiConfig, nil)
}

// EncodeQuery encodes a single query string into embedding
func (e *EmbeddingModel) EncodeQuery(modelName *string, query string, apiConfig *APIConfig) ([]float64, error) {
embeddings, err := e.ModelDriver.Encode(modelName, []string{query}, apiConfig)
if err != nil {
return nil, err
}
if len(embeddings) == 0 {
return nil, fmt.Errorf("no embedding returned")
}
return embeddings[0], nil
}

// RerankModel wraps a ModelDriver with rerank-specific configuration
type RerankModel struct {
ModelDriver ModelDriver
ModelName string
APIConfig *APIConfig
}

// NewRerankModel creates a new RerankModel
func NewRerankModel(driver ModelDriver, modelName string, apiConfig *APIConfig) *RerankModel {
return &RerankModel{
ModelDriver: driver,
ModelName: modelName,
APIConfig: apiConfig,
}
}

// Rerank calculates similarity between query and texts
func (r *RerankModel) Rerank(query string, texts []string, apiConfig *APIConfig) ([]float64, error) {
return r.ModelDriver.Rerank(&r.ModelName, query, texts, apiConfig)
}

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.

🛠️ Refactor suggestion | 🟠 Major

Wrapper API is inconsistent and largely bypassed by callers.

EmbeddingModel.Encode/EncodeQuery re-take modelName *string and apiConfig *APIConfig as arguments and never read the captured e.ModelName / e.APIConfig, while RerankModel.Rerank uses r.ModelName but still re-takes apiConfig. The whole point of wrapping a driver with ModelName+APIConfig is to avoid threading those fields through every call site, so this defeats the abstraction.

In practice, callers already work around the wrapper inconsistency by calling the underlying driver directly — e.g. internal/service/nlp/retrieval.go:600 does embModel.ModelDriver.EncodeQuery(&embModel.ModelName, txt, embModel.APIConfig) rather than embModel.EncodeQuery(...), and the reranker side takes a similar shape. As written, EmbeddingModel.Encode/EncodeQuery are effectively dead code that will diverge from real usage as soon as someone calls them.

Pick one shape and use it everywhere:

♻️ Option A — wrappers own state (recommended; lets callers stop touching ModelDriver)
-// Encode encodes a list of texts into embeddings
-func (e *EmbeddingModel) Encode(modelName *string, texts []string, apiConfig *APIConfig) ([][]float64, error) {
-	return e.ModelDriver.EncodeToEmbedding(modelName, texts, apiConfig, nil)
-}
-
-// EncodeQuery encodes a single query string into embedding
-func (e *EmbeddingModel) EncodeQuery(modelName *string, query string, apiConfig *APIConfig) ([]float64, error) {
-	embeddings, err := e.ModelDriver.Encode(modelName, []string{query}, apiConfig)
+// Encode encodes a list of texts into embeddings
+func (e *EmbeddingModel) Encode(texts []string) ([][]float64, error) {
+	return e.ModelDriver.EncodeToEmbedding(&e.ModelName, texts, e.APIConfig, nil)
+}
+
+// EncodeQuery encodes a single query string into embedding
+func (e *EmbeddingModel) EncodeQuery(query string) ([]float64, error) {
+	embeddings, err := e.ModelDriver.Encode(&e.ModelName, []string{query}, e.APIConfig)
@@
-// Rerank calculates similarity between query and texts
-func (r *RerankModel) Rerank(query string, texts []string, apiConfig *APIConfig) ([]float64, error) {
-	return r.ModelDriver.Rerank(&r.ModelName, query, texts, apiConfig)
-}
+// Rerank calculates similarity between query and texts
+func (r *RerankModel) Rerank(query string, texts []string) ([]float64, error) {
+	return r.ModelDriver.Rerank(&r.ModelName, query, texts, r.APIConfig)
+}

Then update RetrievalService.GetVector and RerankByModel to call embModel.EncodeQuery(txt) / rerankModel.Rerank(query, docs) instead of dereferencing ModelDriver directly.

If you prefer Option B (drop the wrappers and keep driver+name+config tuples on the call boundary), the inconsistency is also resolved — but please don't ship the current half-and-half shape.

📝 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
// Encode encodes a list of texts into embeddings
func (e *EmbeddingModel) Encode(modelName *string, texts []string, apiConfig *APIConfig) ([][]float64, error) {
return e.ModelDriver.EncodeToEmbedding(modelName, texts, apiConfig, nil)
}
// EncodeQuery encodes a single query string into embedding
func (e *EmbeddingModel) EncodeQuery(modelName *string, query string, apiConfig *APIConfig) ([]float64, error) {
embeddings, err := e.ModelDriver.Encode(modelName, []string{query}, apiConfig)
if err != nil {
return nil, err
}
if len(embeddings) == 0 {
return nil, fmt.Errorf("no embedding returned")
}
return embeddings[0], nil
}
// RerankModel wraps a ModelDriver with rerank-specific configuration
type RerankModel struct {
ModelDriver ModelDriver
ModelName string
APIConfig *APIConfig
}
// NewRerankModel creates a new RerankModel
func NewRerankModel(driver ModelDriver, modelName string, apiConfig *APIConfig) *RerankModel {
return &RerankModel{
ModelDriver: driver,
ModelName: modelName,
APIConfig: apiConfig,
}
}
// Rerank calculates similarity between query and texts
func (r *RerankModel) Rerank(query string, texts []string, apiConfig *APIConfig) ([]float64, error) {
return r.ModelDriver.Rerank(&r.ModelName, query, texts, apiConfig)
}
// Encode encodes a list of texts into embeddings
func (e *EmbeddingModel) Encode(texts []string) ([][]float64, error) {
return e.ModelDriver.EncodeToEmbedding(&e.ModelName, texts, e.APIConfig, nil)
}
// EncodeQuery encodes a single query string into embedding
func (e *EmbeddingModel) EncodeQuery(query string) ([]float64, error) {
embeddings, err := e.ModelDriver.Encode(&e.ModelName, []string{query}, e.APIConfig)
if err != nil {
return nil, err
}
if len(embeddings) == 0 {
return nil, fmt.Errorf("no embedding returned")
}
return embeddings[0], nil
}
// RerankModel wraps a ModelDriver with rerank-specific configuration
type RerankModel struct {
ModelDriver ModelDriver
ModelName string
APIConfig *APIConfig
}
// NewRerankModel creates a new RerankModel
func NewRerankModel(driver ModelDriver, modelName string, apiConfig *APIConfig) *RerankModel {
return &RerankModel{
ModelDriver: driver,
ModelName: modelName,
APIConfig: apiConfig,
}
}
// Rerank calculates similarity between query and texts
func (r *RerankModel) Rerank(query string, texts []string) ([]float64, error) {
return r.ModelDriver.Rerank(&r.ModelName, query, texts, r.APIConfig)
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/entity/models/types.go` around lines 92 - 128, The wrapper types are
inconsistent: make the wrappers own state (Option A) by changing
EmbeddingModel.Encode and EncodeQuery to use e.ModelName and e.APIConfig (drop
the modelName/apiConfig params) and change RerankModel.Rerank to use r.ModelName
and r.APIConfig (drop the apiConfig param), then update all call sites (e.g.
RetrievalService.GetVector and RerankByModel and any places currently calling
ModelDriver.Encode/EncodeQuery/Rerank directly) to call
embModel.Encode/EncodeQuery and rerankModel.Rerank on the wrapper instances
instead of dereferencing ModelDriver and passing ModelName/APIConfig manually;
ensure signatures and any interface implementations (ModelDriver usage) are
adjusted to match the new wrapper-owned-params shape.

Comment thread internal/service/model_bundle.go Resolved

@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: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/entity/models/aliyun.go (1)

55-57: ⚠️ Potential issue | 🟠 Major

Critical: AliyunModel.Name() returns wrong provider name.

The method returns "siliconflow" instead of "aliyun". This causes incorrect error messages (e.g., "siliconflow, Encode not implemented" when using Aliyun), misleading logging, and potential issues in provider-based routing logic.

🐛 Proposed fix
 func (z *AliyunModel) Name() string {
-	return "siliconflow"
+	return "aliyun"
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/entity/models/aliyun.go` around lines 55 - 57, The
AliyunModel.Name() function returns the wrong provider string ("siliconflow");
update the method (AliyunModel.Name) to return the correct provider identifier
"aliyun" so logs, error messages and provider routing use the proper name;
locate the AliyunModel type and replace the return value in Name() accordingly
and run/update any tests or usages that assert the provider name.
🤖 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/model_service.go`:
- Around line 896-917: The current logic in getModelConfig incorrectly falls
back to returning providerInfo.ModelDriver when
m.modelDAO.GetModelByProviderIDAndInstanceIDAndModelName(...) succeeds (meaning
the model is present/disabled), letting disabled models be used; change the
conditional so that if GetModelByProviderIDAndInstanceIDAndModelName returns nil
error (model found) you treat it as disabled and return an appropriate error (or
nil driver), and only perform the fallback JSON Unmarshal +
providerInfo.ModelDriver return when the DAO returned an error indicating the
model was not found; apply the same fix to the duplicated block referenced
around lines 919-933 (same functions:
m.modelDAO.GetModelByProviderIDAndInstanceIDAndModelName,
dao.GetModelProviderManager().FindProvider,
dao.GetModelProviderManager().GetModelByName, and the providerInfo.ModelDriver /
modelModule.APIConfig path).

---

Outside diff comments:
In `@internal/entity/models/aliyun.go`:
- Around line 55-57: The AliyunModel.Name() function returns the wrong provider
string ("siliconflow"); update the method (AliyunModel.Name) to return the
correct provider identifier "aliyun" so logs, error messages and provider
routing use the proper name; locate the AliyunModel type and replace the return
value in Name() accordingly and run/update any tests or usages that assert the
provider name.
🪄 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: 95d450d5-c583-4274-a3d1-aee8a243654c

📥 Commits

Reviewing files that changed from the base of the PR and between 6437116 and ae733f6.

📒 Files selected for processing (28)
  • conf/models/siliconflow.json
  • conf/models/zhipu-ai.json
  • internal/entity/models/aliyun.go
  • internal/entity/models/deepseek.go
  • internal/entity/models/dummy.go
  • internal/entity/models/gitee.go
  • internal/entity/models/google.go
  • internal/entity/models/minimax.go
  • internal/entity/models/moonshot.go
  • internal/entity/models/siliconflow.go
  • internal/entity/models/types.go
  • internal/entity/models/zhipu-ai.go
  • internal/entity/types.go
  • internal/handler/providers.go
  • internal/router/router.go
  • internal/service/chunk.go
  • internal/service/model_bundle.go
  • internal/service/model_service.go
  • internal/service/models/deepseek_model.go
  • internal/service/models/factory.go
  • internal/service/models/gitee_model.go
  • internal/service/models/moonshot_model.go
  • internal/service/models/openai_api_compatible_model.go
  • internal/service/models/openai_model.go
  • internal/service/models/siliconflow_model.go
  • internal/service/models/zhipu_model.go
  • internal/service/nlp/reranker.go
  • internal/service/nlp/retrieval.go
💤 Files with no reviewable changes (8)
  • internal/service/models/zhipu_model.go
  • internal/service/models/openai_api_compatible_model.go
  • internal/service/models/moonshot_model.go
  • internal/service/models/deepseek_model.go
  • internal/service/models/openai_model.go
  • internal/service/models/gitee_model.go
  • internal/service/models/siliconflow_model.go
  • internal/service/models/factory.go
✅ Files skipped from review due to trivial changes (3)
  • conf/models/siliconflow.json
  • conf/models/zhipu-ai.json
  • internal/entity/models/moonshot.go
🚧 Files skipped from review as they are similar to previous changes (4)
  • internal/entity/models/google.go
  • internal/entity/models/dummy.go
  • internal/entity/models/gitee.go
  • internal/service/model_bundle.go

Comment on lines +896 to +917
_, err = m.modelDAO.GetModelByProviderIDAndInstanceIDAndModelName(provider.ID, instance.ID, modelName)
if err != nil {
providerInfo := dao.GetModelProviderManager().FindProvider(providerName)
if providerInfo == nil {
return nil, "", nil, fmt.Errorf("provider %s not found", providerName)
}

_, err = dao.GetModelProviderManager().GetModelByName(providerName, modelName)
if err != nil {
return nil, "", nil, fmt.Errorf("provider %s model %s not found", providerName, modelName)
}

var extra map[string]string
err = json.Unmarshal([]byte(instance.Extra), &extra)
if err != nil {
return nil, "", nil, err
}
region := extra["region"]

apiConfig := &modelModule.APIConfig{ApiKey: &instance.APIKey, Region: &region}
return providerInfo.ModelDriver, modelName, apiConfig, 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.

⚠️ Potential issue | 🟠 Major

Disabled model enforcement is bypassed in getModelConfig.

This helper returns a usable model even when GetModelByProviderIDAndInstanceIDAndModelName(...) succeeds (which is treated as disabled in existing service paths), so disabled models can be used again.

Proposed fix
-	_, err = m.modelDAO.GetModelByProviderIDAndInstanceIDAndModelName(provider.ID, instance.ID, modelName)
-	if err != nil {
+	disabledModel, err := m.modelDAO.GetModelByProviderIDAndInstanceIDAndModelName(provider.ID, instance.ID, modelName)
+	if err == nil && disabledModel != nil {
+		return nil, "", nil, fmt.Errorf("model %s is disabled", modelName)
+	}
+	if err != nil {
 		providerInfo := dao.GetModelProviderManager().FindProvider(providerName)
 		if providerInfo == nil {
 			return nil, "", nil, fmt.Errorf("provider %s not found", providerName)
 		}
@@
-		apiConfig := &modelModule.APIConfig{ApiKey: &instance.APIKey, Region: &region}
-		return providerInfo.ModelDriver, modelName, apiConfig, nil
+		apiConfig := &modelModule.APIConfig{ApiKey: &instance.APIKey, Region: &region}
+		return providerInfo.ModelDriver, modelName, apiConfig, nil
 	}

Also applies to: 919-933

🤖 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 896 - 917, The current logic
in getModelConfig incorrectly falls back to returning providerInfo.ModelDriver
when m.modelDAO.GetModelByProviderIDAndInstanceIDAndModelName(...) succeeds
(meaning the model is present/disabled), letting disabled models be used; change
the conditional so that if GetModelByProviderIDAndInstanceIDAndModelName returns
nil error (model found) you treat it as disabled and return an appropriate error
(or nil driver), and only perform the fallback JSON Unmarshal +
providerInfo.ModelDriver return when the DAO returned an error indicating the
model was not found; apply the same fix to the duplicated block referenced
around lines 919-933 (same functions:
m.modelDAO.GetModelByProviderIDAndInstanceIDAndModelName,
dao.GetModelProviderManager().FindProvider,
dao.GetModelProviderManager().GetModelByName, and the providerInfo.ModelDriver /
modelModule.APIConfig path).

@JinHai-CN JinHai-CN added the ci Continue Integration label Apr 28, 2026
@JinHai-CN
JinHai-CN marked this pull request as draft April 28, 2026 04:17
@JinHai-CN
JinHai-CN marked this pull request as ready for review April 28, 2026 04:17
@codecov

codecov Bot commented Apr 28, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95.30%. Comparing base (965717c) to head (ae733f6).
⚠️ Report is 11 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14398   +/-   ##
=======================================
  Coverage   95.30%   95.30%           
=======================================
  Files          10       10           
  Lines         703      703           
  Branches      112      112           
=======================================
  Hits          670      670           
  Misses         16       16           
  Partials       17       17           

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

@JinHai-CN
JinHai-CN merged commit effc84a into infiniflow:main Apr 28, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants