Skip to content

Go: Refactor list-models func - #15900

Merged
JinHai-CN merged 6 commits into
infiniflow:mainfrom
Haruko386:main
Jun 11, 2026
Merged

JinHai-CN merged 6 commits into
infiniflow:mainfrom
Haruko386:main

Conversation

@Haruko386

@Haruko386 Haruko386 commented Jun 10, 2026 •

Copy link
Copy Markdown
Member

What problem does this PR solve?

As title
Issue: #15853

From CLI

RAGFlow(api/default)> list supported models from 'baidu' 'test'
+-----------+------------+---------------+-------------------------------------------+---------------------------------------------+
| dimension | max_tokens | model_types   | name                                      | thinking                                    |
+-----------+------------+---------------+-------------------------------------------+---------------------------------------------+
|           |            |               | qwen3-embedding-4b@Tongyi Lab             |                                             |
|           |            |               | ernie-5.0@Baidu                           |                                             |
|           |            |               | ernie-5.0-thinking-preview@Baidu          |                                             |
|           |            |               | qianfan-ocr-fast@Baidu                    |                                             |
|           |            |               | ernie-5.1@Baidu                           |                                             |
|           |            |               | bge-large-en@BAAI                         |                                             |
|           | 1048576    | [chat]        | deepseek-v4-pro@DeepSeek                  | map[clear_thinking:true default_value:true] |
|           |            |               | qwen3-next-80b-a3b-thinking@Tongyi Lab    |                                             |
|           |            |               | qwen3-next-80b-a3b-instruct@Tongyi Lab    |                                             |
|           |            |               | qwen3.5-35b-a3b@Tongyi Lab                |                                             |
|           |            |               | ernie-4.5-0.3b@Baidu                      |                                             |
|           |            |               | qwen3-14b@Tongyi Lab                      |                                             |
|           |            |               | internvl3-38b@Shanghai AI Lab             |                                             |
|           |            |               | qwen3-embedding-8b@Tongyi Lab             |                                             |
|           |            |               | ernie-x1-turbo-32k-preview@Baidu          |                                             |
|           |            |               | ernie-x1-turbo-32k@Baidu                  |                                             |
|           | 163840     | [chat]        | deepseek-v3.2@DeepSeek                    |                                             |
|           |            |               | qianfan-vl-1.5-flash@Baidu                |                                             |
|           |            |               | glm-5.1@Zhipu                             |                                             |
|           |            |               | ernie-image-turbo@Baidu                   |                                             |
|           |            |               | bge-large-zh@BAAI                         |                                             |
|           |            |               | qwen3-coder-480b-a35b-instruct@Tongyi Lab |                                             |
|           | 204800     | [chat]        | minimax-m2.5@MiniMax                      | map[clear_thinking:true default_value:true] |
|           | 262144     | [vision chat] | kimi-k2.6@其他                                | map[clear_thinking:true default_value:true] |
|           |            |               | qianfan-toytalk@Baidu                     |                                             |
|           |            |               | embedding@Baidu                           |                                             |
|           | 1048576    | [chat]        | deepseek-v4-flash@DeepSeek                | map[clear_thinking:true default_value:true] |
|           | 8192       | [ocr]         | deepseek-ocr@DeepSeek                     |                                             |
|           | 163840     | [chat]        | deepseek-v3@DeepSeek                      |                                             |
|           |            |               | qwen3-vl-30b-a3b-thinking@Tongyi Lab      |                                             |
|           |            |               | qwen3-vl-32b-thinking@Tongyi Lab          |                                             |
|           |            |               | qwen3-vl-32b-instruct@Tongyi Lab          |                                             |
|           |            |               | qianfan-ocr@Baidu                         |                                             |
|           |            |               | qwen3-235b-a22b-thinking-2507@Tongyi Lab  |                                             |
|           |            |               | qwen3-235b-a22b-instruct-2507@Tongyi Lab  |                                             |
|           |            |               | qwen3-coder-30b-a3b-instruct@Tongyi Lab   |                                             |
|           |            |               | qwen3-vl-8b-instruct@Tongyi Lab           |                                             |
|           |            |               | pp-structurev3@Baidu                      |                                             |
|           |            |               | qwen3-embedding-0.6b@Tongyi Lab           |                                             |
|           |            |               | qwen-image@Tongyi Lab                     |                                             |
|           |            |               | qwen3.5-122b-a10b@Tongyi Lab              |                                             |
|           |            |               | paddleocr-vl-0.9b@Baidu                   |                                             |
|           |            |               | ernie-4.5-turbo-20260402@Baidu            |                                             |
|           |            |               | ernie-4.5-turbo-32k@Baidu                 |                                             |
|           |            |               | ernie-4.5-turbo-128k@Baidu                |                                             |
|           |            |               | glm-5@Zhipu                               |                                             |
|           |            |               | ernie-speed-pro-128k@Baidu                |                                             |
|           |            |               | qwen-image-edit@其他                          |                                             |
|           |            |               | qianfan-ipcharacter@Baidu                 |                                             |
|           |            |               | ernie-x1.1@Baidu                          |                                             |
|           |            |               | ernie-x1.1-preview@Baidu                  |                                             |
|           |            |               | tao-8k@其他                                   |                                             |
|           |            |               | qianfan-vl-8b@Baidu                       |                                             |
|           |            |               | deepseek-v3.2-think@DeepSeek              |                                             |
|           |            |               | flux.1-schnell@Black Forest Labs          |                                             |
|           |            |               | qwen3-32b@Tongyi Lab                      |                                             |
|           |            |               | ernie-lite-pro-128k@Baidu                 |                                             |
|           |            |               | ernie-4.5-turbo-vl@Baidu                  |                                             |
|           |            |               | ernie-4.5-turbo-vl-32k@Baidu              |                                             |
|           |            |               | qianfan-check-vl@Baidu                    |                                             |
|           |            |               | qwen3-vl-235b-a22b-thinking@Tongyi Lab    |                                             |
|           |            |               | qwen3-vl-235b-a22b-instruct@Tongyi Lab    |                                             |
|           |            |               | qwen3-vl-30b-a3b-instruct@Tongyi Lab      |                                             |
|           |            |               | qwen3-vl-8b-thinking@Tongyi Lab           |                                             |
|           | 262144     | [vision chat] | kimi-k2.5@其他                                | map[clear_thinking:true default_value:true] |
|           | 131072     | [chat]        | deepseek-r1-distill-qwen-32b@DeepSeek     |                                             |
|           |            |               | qwen3.5-397b-a17b@Tongyi Lab              |                                             |
|           |            |               | qianfan-vl-70b@Baidu                      |                                             |
|           | 131072     | [chat]        | deepseek-r1-distill-qwen-14b@DeepSeek     |                                             |
|           |            |               | qwen3.5-27b@Tongyi Lab                    |                                             |
|           |            |               | qwen3-30b-a3b-thinking-2507@Tongyi Lab    |                                             |
|           |            |               | qwen3-30b-a3b-instruct-2507@Tongyi Lab    |                                             |
|           |            |               | qwen3-8b@Tongyi Lab                       |                                             |
|           |            |               | deepseek-v3.1-250821@DeepSeek             |                                             |
|           |            |               | deepseek-v3.1-think-250821@DeepSeek       |                                             |
|           | 163840     | [chat]        | deepseek-r1-250528@DeepSeek               |                                             |
+-----------+------------+---------------+-------------------------------------------+---------------------------------------------+

Type of change

  • Refactoring

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jun 10, 2026
@Haruko386 Haruko386 removed the size:L This PR changes 100-499 lines, ignoring generated files. label Jun 10, 2026
@dosubot dosubot Bot added the ☯️ refactor Pull request that refactor/refine code label Jun 10, 2026
@Haruko386 Haruko386 added the ci Continue Integration label Jun 10, 2026
@Haruko386
Haruko386 marked this pull request as draft June 10, 2026 07:36
@Haruko386
Haruko386 marked this pull request as ready for review June 10, 2026 07:36
@coderabbitai

coderabbitai Bot commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR standardizes model-list response parsing across 40+ provider implementations by introducing a shared ModelList type and a centralized ParseListModel helper function. Each provider now unmarshals its HTTP response into the typed ModelList structure and delegates conversion to []ListModelResponse to the shared transformation logic, eliminating per-provider boilerplate while adding optional metadata enrichment via provider manager lookups.

Changes

Centralized Model List Parsing

Layer / File(s) Summary
Shared types and centralized parsing helper
internal/entity/models/types.go, internal/entity/models/base_model.go
Add ModelList struct with Object and Models fields; implement ParseListModel to iterate DSModel entries, derive response names (with optional @OwnedBy suffix), and optionally enrich Dimension, MaxTokens, ModelTypes, Thinking via provider manager lookup.
Model type updates for standardized responses
internal/entity/models/deepseek.go
Add OwnedBy field to DSModel in deepseek.go to match the standard ModelList payload shape used across providers.
Simple providers: unmarshal to ModelList and delegate
internal/entity/models/302ai.go, internal/entity/models/baidu.go, internal/entity/models/minimax.go, internal/entity/models/moonshot.go, internal/entity/models/siliconflow.go, internal/entity/models/volcengine.go, internal/entity/models/zhipu-ai.go, internal/entity/models/astraflow.go, internal/entity/models/avian.go, internal/entity/models/azure_openai.go, internal/entity/models/huaweicloud.go, internal/entity/models/huggingface.go, internal/entity/models/hunyuan.go, internal/entity/models/lmstudio.go, internal/entity/models/localai.go, internal/entity/models/mistral.go, internal/entity/models/modelscope.go, internal/entity/models/novita.go, internal/entity/models/nvidia.go, internal/entity/models/openai.go, internal/entity/models/openrouter.go, internal/entity/models/orcarouter.go, internal/entity/models/qiniu.go, internal/entity/models/stepfun.go, internal/entity/models/tokenhub.go, internal/entity/models/tokenpony.go, internal/entity/models/upstage.go, internal/entity/models/vllm.go, internal/entity/models/xai.go, internal/entity/models/xunfei.go
Replace per-provider manual JSON parsing and ListModelResponse construction with direct unmarshal into typed ModelList, nil-check on Models, and delegation to ParseListModel.
Providers with custom DSModel construction
internal/entity/models/cohere.go, internal/entity/models/deepinfra.go, internal/entity/models/google.go, internal/entity/models/gpustack.go, internal/entity/models/groq.go, internal/entity/models/jiekouai.go, internal/entity/models/jina.go, internal/entity/models/longcat.go, internal/entity/models/n1n.go, internal/entity/models/perplexity.go, internal/entity/models/ppio.go, internal/entity/models/togetherai.go, internal/entity/models/xinference.go
Update response struct types to unmarshal data field into []DSModel instead of provider-specific types; construct DSModel entries with custom ID/OwnedBy logic (filtering, trimming, format derivation), then delegate to ParseListModel instead of manually building ListModelResponse.
Enriched model resolution and test validation
internal/entity/models/replicate.go, internal/entity/models/google_test.go
Replicate adds explicit provider-manager lookups to populate Dimension, MaxTokens, ModelTypes, Thinking and changes Name format to name@owner when present; Google tests update fixtures and expectations to use DSModel with ID and OwnedBy fields instead of raw strings, validating composed response names.
CometAPI helper removal
internal/entity/models/cometapi.go
Remove CometAPI-specific parseCometAPIModelCatalog helper function and response types; migrate ListModels to unmarshal into shared ModelList and return ParseListModel(modelList).
Gitee and Aliyun migrations
internal/entity/models/gitee.go, internal/entity/models/aliyun.go
Replace manual iteration with provider-manager lookups and field mapping with unmarshalling into ModelList and delegation to ParseListModel.

Sequence Diagram(s)

sequenceDiagram
  participant HTTPClient as HTTP Client
  participant Provider as Provider.ListModels
  participant ParseListModel as ParseListModel
  participant ProviderMgr as GetProviderManager
  participant APIResponse as ListModelResponse
  HTTPClient->>Provider: Request to /models
  Provider->>Provider: Unmarshal response into ModelList
  Provider->>ParseListModel: ModelList {Models: []DSModel}
  loop For each DSModel
    ParseListModel->>ProviderMgr: GetModelByNameOrAlias(model.ID)
    alt Model found in registry
      ProviderMgr-->>ParseListModel: Model metadata
      ParseListModel->>ParseListModel: Enrich Dimension, MaxTokens, etc.
    else Not found
      ProviderMgr-->>ParseListModel: nil
      ParseListModel->>ParseListModel: Use defaults
    end
    ParseListModel->>ParseListModel: Construct response Name<br/>(ID + `@OwnedBy` if present)
  end
  ParseListModel-->>Provider: []ListModelResponse
  Provider-->>HTTPClient: []ListModelResponse
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • infiniflow/ragflow#15845: Both PRs refactor model-listing implementations and return enriched ListModelResponse entries; this PR centralizes conversion via shared ModelList + ParseListModel, while the related PR adjusts the contract output shaping across similar provider files.

Suggested labels

size:L, refactor, models

Suggested reviewers

  • wangq8

Poem

🐰 Across the warren of model lists so wide,
A single path now guides each provider's stride,
No more the tangled loops of custom parse,
Just ModelList → ParseListModel's grace!
With @OwnedBy names and enrichment bright,
The models hop together, unified in sight! 🌟

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive The PR description includes a relevant issue reference (#15853) and a practical CLI usage example demonstrating the visible impact of the refactoring (enriched model list output). However, it does not include the 'What problem does this PR solve?' narrative section or explicit confirmation of the 'Refactoring' type of change checkbox per the template. Expand the description narrative beyond 'As title' to explain the specific problem being addressed and the benefits of centralizing the list-models parsing logic. Ensure the 'Refactoring' checkbox is explicitly marked.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Go: Refactor list-models func' clearly identifies the primary change—refactoring the list-models function in Go—and is directly related to the changeset, which systematically updates list-models implementations across 40+ model provider files.
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.

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jun 10, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 7

Caution

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

⚠️ Outside diff range comments (1)
conf/all_models.json (1)

327-343: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Split the malformed object: MiniMax-M3 and deepseek-v4-pro-base are merged into one JSON object.

Line 328/Line 329 are duplicated again at Line 332/Line 333 inside the same object, so one model definition is effectively lost/overwritten.

Proposed fix
     {
       "name": "MiniMax-M3",
       "alias": [
         "minimax-m3"
       ],
+      "max_tokens": 1024000,
+      "model_types": [
+        "chat"
+      ],
+      "thinking": {
+        "default_value": true,
+        "clear_thinking": true
+      }
+    },
+    {
       "name": "deepseek-v4-pro-base",
       "alias": [
         "deepseek-v4-pro-base",
         "deepseek/deepseek-v4-pro-base",
         "deepseek-ai/DeepSeek-V4-Pro-Base",
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@conf/all_models.json` around lines 327 - 343, The JSON object merges two
model entries; separate the merged object into two distinct objects: one for
"MiniMax-M3" (alias "minimax-m3") and one for "deepseek-v4-pro-base" (with its
alias array), removing the duplicate name/alias keys so neither model is
overwritten; update the array in conf/all_models.json by creating one object
whose "name" is "MiniMax-M3" and its "alias" contains "minimax-m3", and a second
object whose "name" is "deepseek-v4-pro-base" with the provided alias list and
the "max_tokens" and "model_types" fields preserved for the deepseek entry.

Source: Linters/SAST tools

🧹 Nitpick comments (7)
conf/all_models.json (1)

2-1762: ⚡ Quick win

Add a CI validation step for model-registry uniqueness.

Given the size of this registry, add a JSON validation check that fails on duplicate models[].name and duplicate aliases across entries to prevent future lookup collisions.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@conf/all_models.json` around lines 2 - 1762, Add a CI validation step that
loads conf/all_models.json and fails the build if there are duplicate
models[].name or duplicate alias values (including alias colliding with any
name). Implement a small validator script (e.g.,
scripts/validate_model_registry.py or validate-model-registry.js) that parses
the JSON, collects names and all alias entries, checks for duplicates and
alias/name collisions, prints human-readable duplicate info, and exits non-zero
on failure; then add a CI job (e.g., validate-model-registry) to run that script
on PRs/commits so duplicates are blocked.
internal/entity/models/minimax.go (1)

439-439: ⚡ Quick win

Hoist GetProviderManager() call outside the loop.

GetProviderManager() is called on every iteration. Moving it outside the loop improves efficiency.

♻️ Suggested optimization
 var models []ListModelResponse
+pm := GetProviderManager()
 for _, model := range modelList.Models {
 	modelName := model.ID
 	var modelResponse ListModelResponse
-	pm := GetProviderManager()
 	modelEntity := pm.GetModelByNameOrAlias(modelName)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/entity/models/minimax.go` at line 439, GetProviderManager() is being
invoked on every loop iteration; hoist the call out of the loop by assigning pm
:= GetProviderManager() before entering the loop and then use pm inside the loop
body (replace the in-loop GetProviderManager() usages). This keeps the same pm
variable (pm) in scope and avoids repeated calls to GetProviderManager().
internal/entity/models/302ai.go (1)

927-927: ⚡ Quick win

Hoist GetProviderManager() call outside the loop.

GetProviderManager() is called on every iteration but likely returns the same singleton instance. Moving it outside the loop improves efficiency.

♻️ Suggested optimization
 var models []ListModelResponse
+pm := GetProviderManager()
 for _, model := range modelList.Models {
 	modelName := model.ID
 	var modelResponse ListModelResponse
-	pm := GetProviderManager()
 	modelEntity := pm.GetModelByNameOrAlias(modelName)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/entity/models/302ai.go` at line 927, GetProviderManager() is being
called inside a loop (creating pm each iteration) which is wasteful; move the
call outside the loop and reuse the returned provider manager. Refactor to call
GetProviderManager() once before the loop, assign to a local variable (e.g., pm
:= GetProviderManager()) and remove the repeated call inside the loop so the
loop bodies reference the single pm instance. Ensure any nil checks or
initialization semantics for pm are preserved after hoisting.
internal/entity/models/avian.go (1)

347-347: ⚡ Quick win

Hoist GetProviderManager() call outside the loop.

GetProviderManager() is called on every iteration. Moving it outside the loop improves efficiency.

♻️ Suggested optimization
 var models []ListModelResponse
+pm := GetProviderManager()
 for _, model := range modelList.Models {
 	modelName := model.ID
 	var modelResponse ListModelResponse
-	pm := GetProviderManager()
 	modelEntity := pm.GetModelByNameOrAlias(modelName)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/entity/models/avian.go` at line 347, The call to
GetProviderManager() is being invoked inside the loop; hoist it above the loop
to avoid repeated calls — obtain pm := GetProviderManager() once before
iterating and then use pm within the loop (refer to the GetProviderManager()
call and the loop in the file around the avian model code) so the loop reuses
the same provider manager instance rather than calling GetProviderManager() on
every iteration.
internal/entity/models/aliyun.go (1)

649-649: ⚡ Quick win

Hoist GetProviderManager() call outside the loop.

GetProviderManager() is called on every iteration but likely returns the same singleton. Moving it outside the loop improves efficiency.

♻️ Suggested optimization
 var models []ListModelResponse
+pm := GetProviderManager()
 for _, model := range modelList.Models {
 	modelName := model.ID
 	var modelResponse ListModelResponse
-	pm := GetProviderManager()
 	modelEntity := pm.GetModelByNameOrAlias(modelName)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/entity/models/aliyun.go` at line 649, GetProviderManager() is being
invoked inside the loop (see the pm variable assignment) causing redundant
calls; move the call outside the loop so you obtain pm once before entering the
loop (e.g., declare pm := GetProviderManager() prior to the for/... block) and
then use that pm variable inside the loop (update any references to pm in
functions like whatever uses pm within the loop). Ensure pm is in the correct
scope and its nil/error handling (if any) is done before looping.
internal/entity/models/cometapi.go (1)

257-257: ⚡ Quick win

Hoist GetProviderManager() call outside the loop.

GetProviderManager() is called on every iteration. Moving it outside the loop improves efficiency.

♻️ Suggested optimization
 var models []ListModelResponse
+pm := GetProviderManager()
 for _, model := range modelList.Models {
 	modelName := model.ID
 	var modelResponse ListModelResponse
-	pm := GetProviderManager()
 	modelEntity := pm.GetModelByNameOrAlias(modelName)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/entity/models/cometapi.go` at line 257, GetProviderManager() is
being invoked on every loop iteration (see pm := GetProviderManager()); hoist
this call outside the loop by calling GetProviderManager() once before entering
the loop and reuse the returned pm variable within the loop (replace repeated pm
:= GetProviderManager() lines with a single pm := GetProviderManager() prior to
the loop). Ensure pm is nil-checked once if needed and remove redundant calls
inside functions/methods that already use the loop-scoped pm.
internal/entity/models/baidu.go (1)

801-801: ⚡ Quick win

Hoist GetProviderManager() call outside the loop.

GetProviderManager() is called on every iteration. Moving it outside the loop improves efficiency.

♻️ Suggested optimization
 var models []ListModelResponse
+pm := GetProviderManager()
 for _, model := range modelList.Models {
 	modelName := model.ID
 	var modelResponse ListModelResponse
-	pm := GetProviderManager()
 	modelEntity := pm.GetModelByNameOrAlias(modelName)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/entity/models/baidu.go` at line 801, GetProviderManager() is being
called inside a loop (pm := GetProviderManager()) which causes repeated lookups;
move the call outside the loop by declaring pm := GetProviderManager() once
before the loop that iterates over the items (the loop that currently contains
the pm := GetProviderManager() line) and then use pm within the loop, ensuring
any variables or error handling that depended on per-iteration construction
still work with a single shared provider manager instance.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@conf/all_models.json`:
- Around line 1348-1429: The registry has duplicate model "name" entries in
conf/all_models.json causing InitProviderManager to overwrite earlier mappings
and ParseListModel to return inconsistent metadata; find all duplicated "name"
values (e.g., deepseek-ocr, deepseek-v3, deepseek-v3.2), choose the canonical
entry for each model (or merge required fields like max_tokens, model_types,
thinking into a single canonical object), remove the duplicate entries so every
"name" is unique, and ensure the remaining object contains the correct
consolidated metadata so InitProviderManager and ParseListModel see one
consistent definition per model.

In `@internal/entity/models/302ai.go`:
- Around line 924-931: Ensure model.ID is validated before use in the loop over
modelList.Models: if model.ID is empty, skip processing or log and continue
instead of constructing modelName from an empty ID (which leads to names like ""
or "`@provider`"); update the block that builds modelName (and subsequent lookup
via GetProviderManager().GetModelByNameOrAlias and population of
modelEntity/ListModelResponse) to check model.ID and handle the empty case
(e.g., continue the loop or record an error) so downstream code never operates
on an empty model.ID or produces malformed names when model.OwnedBy is present.

In `@internal/entity/models/aliyun.go`:
- Around line 646-653: The loop over modelList.Models uses model.ID directly to
build modelName and call GetModelByNameOrAlias, which can produce empty or
malformed names; add a guard in the loop that validates model.ID is non-empty
before using it (e.g., if model.ID == "" then log/warn and continue or apply a
clear fallback) so you don't construct names like "`@provider`" or pass an empty
ID into GetModelByNameOrAlias/pm.GetModelByNameOrAlias; ensure the same check is
applied before setting modelName and before calling GetModelByNameOrAlias and
populating ListModelResponse.

In `@internal/entity/models/avian.go`:
- Around line 344-351: Ensure model.ID is validated before use in the loop over
modelList.Models: check if model.ID is empty and if so either skip that entry
(e.g., continue) or set a clear fallback/placeholder and log a warning, rather
than constructing names like model.ID+"@"+model.OwnedBy or calling
pm.GetModelByNameOrAlias with an empty ID; update the loop that references
model.ID, modelName, ListModelResponse, and pm.GetModelByNameOrAlias to perform
this check and handle empty IDs deterministically.

In `@internal/entity/models/baidu.go`:
- Around line 798-805: Inside the loop over modelList.Models, ensure model.ID is
non-empty before using it to build modelName and calling
pm.GetModelByNameOrAlias; if model.ID is empty, skip that model (or set a clear
placeholder like "<unknown_model>") and log or handle the condition to avoid
creating confusing names. Update the block that assigns modelName, constructs
ListModelResponse, and calls GetProviderManager().GetModelByNameOrAlias to first
validate model.ID and early-continue or substitute a safe value when empty.

In `@internal/entity/models/cometapi.go`:
- Around line 254-261: The loop uses model.ID without validating it; before
using model.ID (where modelName is assigned and passed to
GetModelByNameOrAlias), add a guard that checks if model.ID is empty and handle
it (e.g., log a warning via your logger and continue to the next model, or
assign a clear placeholder like "unknown-model" before further processing).
Update the block around modelName := model.ID / modelEntity :=
pm.GetModelByNameOrAlias(modelName) in the same loop to perform this check and
early-continue or fallback so downstream code (ListModelResponse population)
never operates on an empty model.ID.

In `@internal/entity/models/minimax.go`:
- Around line 436-443: The loop in minimax.go uses model.ID directly to build
modelName and call pm.GetModelByNameOrAlias without validating it's non-empty;
add a validation inside the for loop that checks model.ID is not empty before
using it (e.g., if empty, skip this model or set a clear placeholder like
"<unknown-id>" and optionally log/debug), and ensure subsequent uses (building
modelName, assigning to ListModelResponse, and calling GetModelByNameOrAlias)
only occur when the ID is valid or handled. Update the block around variables
modelName, modelResponse, GetProviderManager(), and modelEntity to implement
this guard so you avoid producing confusing names when model.ID is empty.

---

Outside diff comments:
In `@conf/all_models.json`:
- Around line 327-343: The JSON object merges two model entries; separate the
merged object into two distinct objects: one for "MiniMax-M3" (alias
"minimax-m3") and one for "deepseek-v4-pro-base" (with its alias array),
removing the duplicate name/alias keys so neither model is overwritten; update
the array in conf/all_models.json by creating one object whose "name" is
"MiniMax-M3" and its "alias" contains "minimax-m3", and a second object whose
"name" is "deepseek-v4-pro-base" with the provided alias list and the
"max_tokens" and "model_types" fields preserved for the deepseek entry.

---

Nitpick comments:
In `@conf/all_models.json`:
- Around line 2-1762: Add a CI validation step that loads conf/all_models.json
and fails the build if there are duplicate models[].name or duplicate alias
values (including alias colliding with any name). Implement a small validator
script (e.g., scripts/validate_model_registry.py or validate-model-registry.js)
that parses the JSON, collects names and all alias entries, checks for
duplicates and alias/name collisions, prints human-readable duplicate info, and
exits non-zero on failure; then add a CI job (e.g., validate-model-registry) to
run that script on PRs/commits so duplicates are blocked.

In `@internal/entity/models/302ai.go`:
- Line 927: GetProviderManager() is being called inside a loop (creating pm each
iteration) which is wasteful; move the call outside the loop and reuse the
returned provider manager. Refactor to call GetProviderManager() once before the
loop, assign to a local variable (e.g., pm := GetProviderManager()) and remove
the repeated call inside the loop so the loop bodies reference the single pm
instance. Ensure any nil checks or initialization semantics for pm are preserved
after hoisting.

In `@internal/entity/models/aliyun.go`:
- Line 649: GetProviderManager() is being invoked inside the loop (see the pm
variable assignment) causing redundant calls; move the call outside the loop so
you obtain pm once before entering the loop (e.g., declare pm :=
GetProviderManager() prior to the for/... block) and then use that pm variable
inside the loop (update any references to pm in functions like whatever uses pm
within the loop). Ensure pm is in the correct scope and its nil/error handling
(if any) is done before looping.

In `@internal/entity/models/avian.go`:
- Line 347: The call to GetProviderManager() is being invoked inside the loop;
hoist it above the loop to avoid repeated calls — obtain pm :=
GetProviderManager() once before iterating and then use pm within the loop
(refer to the GetProviderManager() call and the loop in the file around the
avian model code) so the loop reuses the same provider manager instance rather
than calling GetProviderManager() on every iteration.

In `@internal/entity/models/baidu.go`:
- Line 801: GetProviderManager() is being called inside a loop (pm :=
GetProviderManager()) which causes repeated lookups; move the call outside the
loop by declaring pm := GetProviderManager() once before the loop that iterates
over the items (the loop that currently contains the pm := GetProviderManager()
line) and then use pm within the loop, ensuring any variables or error handling
that depended on per-iteration construction still work with a single shared
provider manager instance.

In `@internal/entity/models/cometapi.go`:
- Line 257: GetProviderManager() is being invoked on every loop iteration (see
pm := GetProviderManager()); hoist this call outside the loop by calling
GetProviderManager() once before entering the loop and reuse the returned pm
variable within the loop (replace repeated pm := GetProviderManager() lines with
a single pm := GetProviderManager() prior to the loop). Ensure pm is nil-checked
once if needed and remove redundant calls inside functions/methods that already
use the loop-scoped pm.

In `@internal/entity/models/minimax.go`:
- Line 439: GetProviderManager() is being invoked on every loop iteration; hoist
the call out of the loop by assigning pm := GetProviderManager() before entering
the loop and then use pm inside the loop body (replace the in-loop
GetProviderManager() usages). This keeps the same pm variable (pm) in scope and
avoids repeated calls to GetProviderManager().
🪄 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: ce73e149-2e52-41e4-8203-f45ed5c77f30

📥 Commits

Reviewing files that changed from the base of the PR and between dcf623d and 815e91b.

📒 Files selected for processing (15)
  • conf/all_models.json
  • internal/entity/models/302ai.go
  • internal/entity/models/aliyun.go
  • internal/entity/models/avian.go
  • internal/entity/models/baidu.go
  • internal/entity/models/base_model.go
  • internal/entity/models/cometapi.go
  • internal/entity/models/deepseek.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/volcengine.go
  • internal/entity/models/zhipu-ai.go

Comment thread conf/all_models.json Resolved
Comment thread internal/entity/models/302ai.go Outdated
Comment on lines 924 to 931
for _, model := range modelList.Models {
modelName := model.ID
var modelResponse ListModelResponse
pm := GetProviderManager()
modelEntity := pm.GetModelByNameOrAlias(modelName)
if model.OwnedBy != "" {
modelName = model.ID + "@" + model.OwnedBy
}

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

Validate that model.ID is non-empty before use.

The code uses model.ID without checking if it's empty. If the API returns a model with an empty ID, the result could be a model named "" (when OwnedBy is absent) or "@Provider" (when OwnedBy is present), which would be confusing.

🛡️ Suggested validation
 for _, model := range modelList.Models {
 	modelName := model.ID
+	if strings.TrimSpace(modelName) == "" {
+		continue
+	}
 	var modelResponse ListModelResponse
 	pm := GetProviderManager()
 	modelEntity := pm.GetModelByNameOrAlias(modelName)
📝 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
for _, model := range modelList.Models {
modelName := model.ID
var modelResponse ListModelResponse
pm := GetProviderManager()
modelEntity := pm.GetModelByNameOrAlias(modelName)
if model.OwnedBy != "" {
modelName = model.ID + "@" + model.OwnedBy
}
for _, model := range modelList.Models {
modelName := model.ID
if strings.TrimSpace(modelName) == "" {
continue
}
var modelResponse ListModelResponse
pm := GetProviderManager()
modelEntity := pm.GetModelByNameOrAlias(modelName)
if model.OwnedBy != "" {
modelName = model.ID + "@" + model.OwnedBy
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/entity/models/302ai.go` around lines 924 - 931, Ensure model.ID is
validated before use in the loop over modelList.Models: if model.ID is empty,
skip processing or log and continue instead of constructing modelName from an
empty ID (which leads to names like "" or "`@provider`"); update the block that
builds modelName (and subsequent lookup via
GetProviderManager().GetModelByNameOrAlias and population of
modelEntity/ListModelResponse) to check model.ID and handle the empty case
(e.g., continue the loop or record an error) so downstream code never operates
on an empty model.ID or produces malformed names when model.OwnedBy is present.

Comment thread internal/entity/models/aliyun.go Outdated
Comment on lines +646 to +653
for _, model := range modelList.Models {
modelName := model.ID
var modelResponse ListModelResponse
pm := GetProviderManager()
modelEntity := pm.GetModelByNameOrAlias(modelName)
if model.OwnedBy != "" {
modelName = model.ID + "@" + model.OwnedBy
}

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

Validate that model.ID is non-empty before use.

The code uses model.ID without checking if it's empty, which could result in confusing model names like "" or "@Provider".

🛡️ Suggested validation
 for _, model := range modelList.Models {
 	modelName := model.ID
+	if strings.TrimSpace(modelName) == "" {
+		continue
+	}
 	var modelResponse ListModelResponse
 	pm := GetProviderManager()
 	modelEntity := pm.GetModelByNameOrAlias(modelName)
📝 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
for _, model := range modelList.Models {
modelName := model.ID
var modelResponse ListModelResponse
pm := GetProviderManager()
modelEntity := pm.GetModelByNameOrAlias(modelName)
if model.OwnedBy != "" {
modelName = model.ID + "@" + model.OwnedBy
}
for _, model := range modelList.Models {
modelName := model.ID
if strings.TrimSpace(modelName) == "" {
continue
}
var modelResponse ListModelResponse
pm := GetProviderManager()
modelEntity := pm.GetModelByNameOrAlias(modelName)
if model.OwnedBy != "" {
modelName = model.ID + "@" + model.OwnedBy
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/entity/models/aliyun.go` around lines 646 - 653, The loop over
modelList.Models uses model.ID directly to build modelName and call
GetModelByNameOrAlias, which can produce empty or malformed names; add a guard
in the loop that validates model.ID is non-empty before using it (e.g., if
model.ID == "" then log/warn and continue or apply a clear fallback) so you
don't construct names like "`@provider`" or pass an empty ID into
GetModelByNameOrAlias/pm.GetModelByNameOrAlias; ensure the same check is applied
before setting modelName and before calling GetModelByNameOrAlias and populating
ListModelResponse.

Comment thread internal/entity/models/avian.go Outdated
Comment on lines +344 to +351
for _, model := range modelList.Models {
modelName := model.ID
var modelResponse ListModelResponse
pm := GetProviderManager()
modelEntity := pm.GetModelByNameOrAlias(modelName)
if model.OwnedBy != "" {
modelName = model.ID + "@" + model.OwnedBy
}

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

Validate that model.ID is non-empty before use.

The code uses model.ID without checking if it's empty, which could result in confusing model names.

🛡️ Suggested validation
 for _, model := range modelList.Models {
 	modelName := model.ID
+	if strings.TrimSpace(modelName) == "" {
+		continue
+	}
 	var modelResponse ListModelResponse
 	pm := GetProviderManager()
 	modelEntity := pm.GetModelByNameOrAlias(modelName)
📝 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
for _, model := range modelList.Models {
modelName := model.ID
var modelResponse ListModelResponse
pm := GetProviderManager()
modelEntity := pm.GetModelByNameOrAlias(modelName)
if model.OwnedBy != "" {
modelName = model.ID + "@" + model.OwnedBy
}
for _, model := range modelList.Models {
modelName := model.ID
if strings.TrimSpace(modelName) == "" {
continue
}
var modelResponse ListModelResponse
pm := GetProviderManager()
modelEntity := pm.GetModelByNameOrAlias(modelName)
if model.OwnedBy != "" {
modelName = model.ID + "@" + model.OwnedBy
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/entity/models/avian.go` around lines 344 - 351, Ensure model.ID is
validated before use in the loop over modelList.Models: check if model.ID is
empty and if so either skip that entry (e.g., continue) or set a clear
fallback/placeholder and log a warning, rather than constructing names like
model.ID+"@"+model.OwnedBy or calling pm.GetModelByNameOrAlias with an empty ID;
update the loop that references model.ID, modelName, ListModelResponse, and
pm.GetModelByNameOrAlias to perform this check and handle empty IDs
deterministically.

Comment thread internal/entity/models/baidu.go Resolved
Comment thread internal/entity/models/cometapi.go Outdated
Comment on lines +254 to +261
for _, model := range modelList.Models {
modelName := model.ID
var modelResponse ListModelResponse
pm := GetProviderManager()
modelEntity := pm.GetModelByNameOrAlias(modelName)
if model.OwnedBy != "" {
modelName = model.ID + "@" + model.OwnedBy
}

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

Validate that model.ID is non-empty before use.

The code uses model.ID without checking if it's empty, which could result in confusing model names.

🛡️ Suggested validation
 for _, model := range modelList.Models {
 	modelName := model.ID
+	if strings.TrimSpace(modelName) == "" {
+		continue
+	}
 	var modelResponse ListModelResponse
 	pm := GetProviderManager()
 	modelEntity := pm.GetModelByNameOrAlias(modelName)
📝 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
for _, model := range modelList.Models {
modelName := model.ID
var modelResponse ListModelResponse
pm := GetProviderManager()
modelEntity := pm.GetModelByNameOrAlias(modelName)
if model.OwnedBy != "" {
modelName = model.ID + "@" + model.OwnedBy
}
for _, model := range modelList.Models {
modelName := model.ID
if strings.TrimSpace(modelName) == "" {
continue
}
var modelResponse ListModelResponse
pm := GetProviderManager()
modelEntity := pm.GetModelByNameOrAlias(modelName)
if model.OwnedBy != "" {
modelName = model.ID + "@" + model.OwnedBy
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/entity/models/cometapi.go` around lines 254 - 261, The loop uses
model.ID without validating it; before using model.ID (where modelName is
assigned and passed to GetModelByNameOrAlias), add a guard that checks if
model.ID is empty and handle it (e.g., log a warning via your logger and
continue to the next model, or assign a clear placeholder like "unknown-model"
before further processing). Update the block around modelName := model.ID /
modelEntity := pm.GetModelByNameOrAlias(modelName) in the same loop to perform
this check and early-continue or fallback so downstream code (ListModelResponse
population) never operates on an empty model.ID.

Comment thread internal/entity/models/minimax.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.

🧹 Nitpick comments (1)
internal/entity/models/cometapi.go (1)

508-514: Ensure DSModel matches CometAPI /models and clean up leftover catalog types

  • DSModel (in internal/entity/models/deepseek.go) defines ID string \json:"id"`andOwnedBy string `json:"owned_by"`, which fits the ModelList→ParseListModel(modelList)parsing used ininternal/entity/models/cometapi.go` (lines 508-514).
  • cometapiModelCatalogResponse / cometapiModelCatalogItem type definitions still exist in internal/entity/models/cometapi.go but no longer appear referenced; remove them as dead code to avoid confusion.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/entity/models/cometapi.go` around lines 508 - 514, Update DSModel in
internal/entity/models/deepseek.go to match the CometAPI /models payload (ensure
it defines ID string `json:"id"` and OwnedBy string `json:"owned_by"` so
ParseListModel(ModelList) unmarshalling aligns), verify the ModelList type used
by ParseListModel matches the CometAPI response fields, and remove the
now-unused cometapiModelCatalogResponse and cometapiModelCatalogItem type
definitions from cometapi.go to eliminate dead code and confusion.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@internal/entity/models/cometapi.go`:
- Around line 508-514: Update DSModel in internal/entity/models/deepseek.go to
match the CometAPI /models payload (ensure it defines ID string `json:"id"` and
OwnedBy string `json:"owned_by"` so ParseListModel(ModelList) unmarshalling
aligns), verify the ModelList type used by ParseListModel matches the CometAPI
response fields, and remove the now-unused cometapiModelCatalogResponse and
cometapiModelCatalogItem type definitions from cometapi.go to eliminate dead
code and confusion.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: a19b173b-006e-4f20-9c5b-178e7d9f1dc2

📥 Commits

Reviewing files that changed from the base of the PR and between 815e91b and 50692b9.

📒 Files selected for processing (1)
  • internal/entity/models/cometapi.go

@codecov

codecov Bot commented Jun 10, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (478c984) to head (99c9e13).
⚠️ Report is 23 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15900   +/-   ##
=======================================
  Coverage   93.16%   93.16%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          668      668           
  Misses         29       29           
  Partials       20       20           

☔ View full report in Codecov by Harness.
📢 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.

@Haruko386
Haruko386 marked this pull request as draft June 10, 2026 08:28
@Haruko386 Haruko386 changed the title Go: Add some models and refactor list-models func Go: Refactor list-models func Jun 10, 2026
@tmimmanuel tmimmanuel mentioned this pull request Jun 10, 2026
2 of 6 tasks
@Haruko386
Haruko386 marked this pull request as ready for review June 11, 2026 03:29
@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jun 11, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 6

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/base_model.go (1)

86-96: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Shared root cause: ParseListModel does not validate model.ID across all providers.

ParseListModel in base_model.go uses model.ID without validating it is non-empty. This affects multiple providers:

  • GPUStack, Groq, Perplexity: Previously filtered empty IDs themselves; refactor removes that guard.
  • Huaweicloud, LmStudio, Aliyun: Never validated per-model IDs; now delegate to ParseListModel which also doesn't validate.

When upstream APIs return models with empty IDs, the output contains confusing names like "" or "@<provider>". The fix should be centralized in ParseListModel (either skip empty IDs or fail fast, matching the pattern in jiekouai.go lines 593-599).

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/entity/models/base_model.go` around lines 86 - 96, In
ParseListModel, validate each model's ID before using it: inside the loop over
modelList.Models check that model.ID is non-empty and either skip that entry or
return an error (consistent with the jiekouai.go pattern around lines 593-599);
ensure you update the handling around model.ID/modelName and the creation of
modelResponse (references: ParseListModel, modelList.Models loop, variable
model.ID, modelResponse, and modelEntity/GetModelByNameOrAlias) so no downstream
code constructs names like "" or "`@provider`" from empty IDs.
internal/entity/models/avian.go (1)

338-343: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Add nil check for modelList.Models to match other providers.

All other providers in this PR (openai, openrouter, orcarouter, qiniu, stepfun, tokenhub) validate that modelList.Models is non-nil after unmarshalling and before calling ParseListModel. Without this check, if the API returns {"data": null} or omits the data field entirely, avian will silently return an empty model list, while other providers will return "invalid models list format".

🛡️ Proposed fix
 var modelList ModelList
 if err = json.Unmarshal(body, &modelList); err != nil {
 	return nil, fmt.Errorf("failed to parse response: %w", err)
 }
+if modelList.Models == nil {
+	return nil, fmt.Errorf("invalid models list format")
+}
 
 return ParseListModel(modelList), nil
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/entity/models/avian.go` around lines 338 - 343, After unmarshalling
into modelList in the function that reads avian models, add a nil-check for
modelList.Models and return an error matching other providers when it's nil;
specifically, after the json.Unmarshal error check, verify that modelList.Models
!= nil and if it is nil return nil, fmt.Errorf("invalid models list format")
instead of calling ParseListModel(modelList), ensuring the code path mirrors the
other providers (check variables modelList.Models and the call to
ParseListModel).
internal/entity/models/replicate.go (1)

734-734: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Incomplete comment: sentence fragment.

The comment "normalizes Replicate's two observed" ends mid-sentence without explaining what the two observed shapes are. Looking at the similar pattern in replicateEmbedInput (lines 605-617), detailed schema documentation is helpful for understanding the upstream API contracts.

📝 Suggested comment completion

Based on the function body (lines 736-751), the two shapes are:

  1. Bare array of floats
  2. Object with a scores field
-// replicateRerankOutputToScores normalizes Replicate's two observed
+// replicateRerankOutputToScores normalizes Replicate's two observed
+// rerank-output shapes into a []float64 aligned with input order:
+//
+//   []floats              — bare array of scores
+//   {scores: []floats}    — object wrapper with scores field
 func replicateRerankOutputToScores(output interface{}, n int) ([]float64, error) {
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/entity/models/replicate.go` at line 734, Update the incomplete
comment for the function replicateRerankOutputToScores: replace the fragment
"normalizes Replicate's two observed" with a full description of the two
observed response shapes this function handles (1) a bare array of floats and
(2) an object containing a scores field (e.g., {"scores": [...]}); mirror the
schema-style documentation used in replicateEmbedInput to make the upstream API
contract explicit and include any example shapes or types expected by the
function.
🧹 Nitpick comments (9)
internal/entity/models/ppio.go (1)

308-310: 💤 Low value

Remove unused ppioModelInfo struct.

This struct is no longer referenced after the refactor.

🧹 Proposed cleanup
-type ppioModelInfo struct {
-	ID string `json:"id"`
-}
-
 type ppioListModelsResponse struct {
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/entity/models/ppio.go` around lines 308 - 310, The ppioModelInfo
struct is unused after the refactor; remove the declaration of ppioModelInfo
from internal/entity/models/ppio.go to clean up dead code and avoid unused-type
warnings, and run tests/build to ensure nothing else references ppioModelInfo
(search for the symbol ppioModelInfo to confirm no remaining usages before
committing).
internal/entity/models/longcat.go (1)

340-342: 💤 Low value

Remove unused longCatModelInfo struct.

After the refactor to DSModel, this struct is no longer referenced.

🧹 Proposed cleanup
-type longCatModelInfo struct {
-	ID string `json:"id"`
-}
-
 type longCatListModelsResponse struct {
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/entity/models/longcat.go` around lines 340 - 342, Remove the unused
type declaration longCatModelInfo (the struct with ID string `json:"id"`) since
DSModel replaces it; delete the entire type block from longcat.go and run `go
vet`/`go build` to ensure no remaining references, and if that removal makes any
imports unused in the file, remove those imports as well.
internal/entity/models/n1n.go (1)

526-528: 💤 Low value

Remove unused n1nModelCatalogItem struct.

This struct is no longer used after switching to DSModel.

🧹 Proposed cleanup
-type n1nModelCatalogItem struct {
-	ID string `json:"id"`
-}
-
 type n1nModelCatalogResponse struct {
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/entity/models/n1n.go` around lines 526 - 528, Remove the unused
n1nModelCatalogItem struct declaration: locate the type definition named
n1nModelCatalogItem in internal/entity/models/n1n.go and delete it, ensuring
there are no remaining references (replace usages with DSModel if any remain);
run a build/static-check to confirm no references remain and update imports or
comments if necessary.
internal/entity/models/orcarouter.go (1)

461-462: 💤 Low value

Remove duplicate comment.

Lines 461-462 both contain // Parse response.

♻️ Proposed fix
-// Parse response
 // Parse response
 var modelList ModelList
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/entity/models/orcarouter.go` around lines 461 - 462, Remove the
duplicated comment line "// Parse response" that appears immediately before the
declaration of the variable ModelList (var modelList ModelList) so only one
explanatory comment remains; locate the block around the modelList declaration
(the parsing section) and delete the redundant comment line.
internal/entity/models/openrouter.go (1)

789-790: 💤 Low value

Remove duplicate comment.

Lines 789-790 both contain // Parse response.

♻️ Proposed fix
-// Parse response
 // Parse response
 var modelList ModelList
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/entity/models/openrouter.go` around lines 789 - 790, Remove the
duplicate comment "// Parse response" so only one instance remains immediately
above the variable declaration for modelList (var modelList ModelList); edit
around the ModelList/modelList declaration to delete the redundant comment and
keep a single, clear "// Parse response" line.
internal/entity/models/tokenhub.go (1)

500-501: 💤 Low value

Remove duplicate comment.

Lines 500-501 both contain // Parse response.

♻️ Proposed fix
-// Parse response
 // Parse response
 var modelList ModelList
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/entity/models/tokenhub.go` around lines 500 - 501, There are two
identical comments "// Parse response" adjacent to the ModelList declaration in
tokenhub.go; remove the duplicate so only a single "// Parse response" remains
immediately above the ModelList var declaration (the code around the ModelList
type/variable is what to edit).
internal/entity/models/xai.go (1)

409-410: 💤 Low value

Remove duplicate comment.

Line 409 and line 410 both contain // Parse response.

🧹 Suggested cleanup
-	// Parse response
 	// Parse response
 	var modelList ModelList
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/entity/models/xai.go` around lines 409 - 410, Remove the duplicate
comment "// Parse response" in internal/entity/models/xai.go so only a single
comment remains; locate the consecutive comments labeled "Parse response" in the
parsing block (around the response parsing logic) and delete the redundant line
to keep the code clean and avoid duplicated comments.
internal/entity/models/xunfei.go (1)

432-433: 💤 Low value

Remove duplicate comment.

Line 432 and line 433 both contain // Parse response.

🧹 Suggested cleanup
-	// Parse response
 	// Parse response
 	var modelList ModelList
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/entity/models/xunfei.go` around lines 432 - 433, Remove the
duplicated comment line "// Parse response" so only a single instance remains;
locate the duplicate comments (both lines containing the exact text "// Parse
response") in internal/entity/models/xunfei.go and delete one to avoid redundant
comments, leaving the single, intended comment above the parsing code (no code
changes required).
internal/entity/models/vllm.go (1)

533-534: 💤 Low value

Remove duplicate comment.

Line 533 and line 534 both contain // Parse response.

🧹 Suggested cleanup
-	// Parse response
 	// Parse response
 	var modelList ModelList
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/entity/models/vllm.go` around lines 533 - 534, Remove the duplicated
comment string "// Parse response" in internal/entity/models/vllm.go so only a
single instance remains; locate the two consecutive comment lines with that
exact text in the response-parsing block and delete one of them (leave a single
"// Parse response" above the parsing logic).
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/entity/models/jina.go`:
- Line 360: The direct chained assertion
model.(map[string]interface{})["name"].(string) can panic; update the code
around the modelName assignment to perform safe type checks: first assert model
is a map[string]interface{} (e.g., m, ok := model.(map[string]interface{})),
then check the "name" key exists (val, ok := m["name"]) and that val is a string
(s, ok := val.(string)); if any check fails, either skip the malformed entry or
return a descriptive error (include the offending value/context) instead of
allowing a panic, and use the validated string (s) as modelName. Ensure you
modify the surrounding logic that consumes modelName to handle the skip/error
path accordingly.
- Line 358: The allocation of models uses an unchecked type assertion
result["data"].([]interface{}) which can panic; first extract and check the type
like data, ok := result["data"].([]interface{}) (and treat nil as empty) and
then preallocate models using len(data) only when ok is true, otherwise set
models = make([]DSModel, 0) and handle the malformed/nil case (e.g., log or
return an error) so DSModel slice creation never panics.

In `@internal/entity/models/longcat.go`:
- Line 401: ParseListModel currently appends entries even when model.ID is
empty/whitespace; update ParseListModel (the function handling ModelList and
modelResponse.Name) to skip such entries by adding a guard like if
strings.TrimSpace(model.ID) == "" { continue } before constructing modelName and
appending to the response slice so empty IDs (or "`@OwnedBy`" cases) are not
included in the returned ModelList; ensure you import strings if not already.

In `@internal/entity/models/replicate.go`:
- Around line 548-567: The loop over result.Results must skip entries with empty
model.Name to avoid producing names like "`@owner`" or empty Name fields; inside
the for loop (where modelName := model.Name and modelResponse.Name is set) add a
guard that if model.Name is empty (after trimming) then continue, ensuring you
do not call pm.GetModelByNameOrAlias or construct a ListModelResponse for that
item; keep existing logic for combining model.Name and model.Owner and
populating fields from modelEntity (from pm.GetModelByNameOrAlias) unchanged for
valid names.
- Around line 547-567: The loop in replicate.go currently formats
ListModelResponse.Name as "name@owner" and can append entries when model.Name is
empty; change the formatting to "owner/name" when model.Owner is non-empty
(i.e., set modelResponse.Name = model.Owner + "/" + model.Name) to match
replicate_test.go expectations, and add a guard to skip any result where
model.Name is empty before constructing modelResponse and appending to models;
keep existing enrichment from pm.GetModelByNameOrAlias (modelEntity) intact when
present.

In `@internal/entity/models/togetherai.go`:
- Around line 355-360: The change removed filtering of DSModel entries with
empty ID, causing models with empty Name to surface; fix by filtering the
unmarshaled result slice (variable result of type []DSModel) to exclude any
DSModel where ID == "" before constructing ModelList and calling
ParseListModel(ModelList{Models: filtered}). Ensure you perform the filter right
after json.Unmarshal and pass the filtered slice (not the original result) into
ParseListModel.

---

Outside diff comments:
In `@internal/entity/models/avian.go`:
- Around line 338-343: After unmarshalling into modelList in the function that
reads avian models, add a nil-check for modelList.Models and return an error
matching other providers when it's nil; specifically, after the json.Unmarshal
error check, verify that modelList.Models != nil and if it is nil return nil,
fmt.Errorf("invalid models list format") instead of calling
ParseListModel(modelList), ensuring the code path mirrors the other providers
(check variables modelList.Models and the call to ParseListModel).

In `@internal/entity/models/base_model.go`:
- Around line 86-96: In ParseListModel, validate each model's ID before using
it: inside the loop over modelList.Models check that model.ID is non-empty and
either skip that entry or return an error (consistent with the jiekouai.go
pattern around lines 593-599); ensure you update the handling around
model.ID/modelName and the creation of modelResponse (references:
ParseListModel, modelList.Models loop, variable model.ID, modelResponse, and
modelEntity/GetModelByNameOrAlias) so no downstream code constructs names like
"" or "`@provider`" from empty IDs.

In `@internal/entity/models/replicate.go`:
- Line 734: Update the incomplete comment for the function
replicateRerankOutputToScores: replace the fragment "normalizes Replicate's two
observed" with a full description of the two observed response shapes this
function handles (1) a bare array of floats and (2) an object containing a
scores field (e.g., {"scores": [...]}); mirror the schema-style documentation
used in replicateEmbedInput to make the upstream API contract explicit and
include any example shapes or types expected by the function.

---

Nitpick comments:
In `@internal/entity/models/longcat.go`:
- Around line 340-342: Remove the unused type declaration longCatModelInfo (the
struct with ID string `json:"id"`) since DSModel replaces it; delete the entire
type block from longcat.go and run `go vet`/`go build` to ensure no remaining
references, and if that removal makes any imports unused in the file, remove
those imports as well.

In `@internal/entity/models/n1n.go`:
- Around line 526-528: Remove the unused n1nModelCatalogItem struct declaration:
locate the type definition named n1nModelCatalogItem in
internal/entity/models/n1n.go and delete it, ensuring there are no remaining
references (replace usages with DSModel if any remain); run a build/static-check
to confirm no references remain and update imports or comments if necessary.

In `@internal/entity/models/openrouter.go`:
- Around line 789-790: Remove the duplicate comment "// Parse response" so only
one instance remains immediately above the variable declaration for modelList
(var modelList ModelList); edit around the ModelList/modelList declaration to
delete the redundant comment and keep a single, clear "// Parse response" line.

In `@internal/entity/models/orcarouter.go`:
- Around line 461-462: Remove the duplicated comment line "// Parse response"
that appears immediately before the declaration of the variable ModelList (var
modelList ModelList) so only one explanatory comment remains; locate the block
around the modelList declaration (the parsing section) and delete the redundant
comment line.

In `@internal/entity/models/ppio.go`:
- Around line 308-310: The ppioModelInfo struct is unused after the refactor;
remove the declaration of ppioModelInfo from internal/entity/models/ppio.go to
clean up dead code and avoid unused-type warnings, and run tests/build to ensure
nothing else references ppioModelInfo (search for the symbol ppioModelInfo to
confirm no remaining usages before committing).

In `@internal/entity/models/tokenhub.go`:
- Around line 500-501: There are two identical comments "// Parse response"
adjacent to the ModelList declaration in tokenhub.go; remove the duplicate so
only a single "// Parse response" remains immediately above the ModelList var
declaration (the code around the ModelList type/variable is what to edit).

In `@internal/entity/models/vllm.go`:
- Around line 533-534: Remove the duplicated comment string "// Parse response"
in internal/entity/models/vllm.go so only a single instance remains; locate the
two consecutive comment lines with that exact text in the response-parsing block
and delete one of them (leave a single "// Parse response" above the parsing
logic).

In `@internal/entity/models/xai.go`:
- Around line 409-410: Remove the duplicate comment "// Parse response" in
internal/entity/models/xai.go so only a single comment remains; locate the
consecutive comments labeled "Parse response" in the parsing block (around the
response parsing logic) and delete the redundant line to keep the code clean and
avoid duplicated comments.

In `@internal/entity/models/xunfei.go`:
- Around line 432-433: Remove the duplicated comment line "// Parse response" so
only a single instance remains; locate the duplicate comments (both lines
containing the exact text "// Parse response") in
internal/entity/models/xunfei.go and delete one to avoid redundant comments,
leaving the single, intended comment above the parsing code (no code changes
required).
🪄 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: f775637a-ee12-4926-9d78-adf64c585d45

📥 Commits

Reviewing files that changed from the base of the PR and between 1b54238 and 99c9e13.

📒 Files selected for processing (42)
  • internal/entity/models/302ai.go
  • internal/entity/models/aliyun.go
  • internal/entity/models/astraflow.go
  • internal/entity/models/avian.go
  • internal/entity/models/azure_openai.go
  • internal/entity/models/base_model.go
  • internal/entity/models/cohere.go
  • internal/entity/models/deepinfra.go
  • internal/entity/models/google.go
  • internal/entity/models/google_test.go
  • internal/entity/models/gpustack.go
  • internal/entity/models/groq.go
  • internal/entity/models/huaweicloud.go
  • internal/entity/models/huggingface.go
  • internal/entity/models/hunyuan.go
  • internal/entity/models/jiekouai.go
  • internal/entity/models/jina.go
  • internal/entity/models/lmstudio.go
  • internal/entity/models/localai.go
  • internal/entity/models/longcat.go
  • internal/entity/models/minimax.go
  • internal/entity/models/mistral.go
  • internal/entity/models/modelscope.go
  • internal/entity/models/n1n.go
  • internal/entity/models/novita.go
  • internal/entity/models/nvidia.go
  • internal/entity/models/openai.go
  • internal/entity/models/openrouter.go
  • internal/entity/models/orcarouter.go
  • internal/entity/models/perplexity.go
  • internal/entity/models/ppio.go
  • internal/entity/models/qiniu.go
  • internal/entity/models/replicate.go
  • internal/entity/models/stepfun.go
  • internal/entity/models/togetherai.go
  • internal/entity/models/tokenhub.go
  • internal/entity/models/tokenpony.go
  • internal/entity/models/upstage.go
  • internal/entity/models/vllm.go
  • internal/entity/models/xai.go
  • internal/entity/models/xinference.go
  • internal/entity/models/xunfei.go


// convert result["data"] to []map[string]interface{}
models := make([]ListModelResponse, 0)
models := make([]DSModel, 0, len(result["data"].([]interface{})))

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

Unchecked type assertion will panic on malformed or nil response.

Line 358 performs an unchecked type assertion result["data"].([]interface{}) inside the len() call. If the upstream API returns result["data"] as nil or a type other than []interface{}, this will panic at runtime.

Add a safe type assertion with an ok check before the preallocation.

🛡️ Proposed fix with safe type assertion
-	models := make([]DSModel, 0, len(result["data"].([]interface{})))
-	for _, model := range result["data"].([]interface{}) {
+	dataSlice, ok := result["data"].([]interface{})
+	if !ok {
+		return nil, fmt.Errorf("failed to parse response: data field is not an array")
+	}
+	models := make([]DSModel, 0, len(dataSlice))
+	for _, model := range dataSlice {
📝 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
models := make([]DSModel, 0, len(result["data"].([]interface{})))
dataSlice, ok := result["data"].([]interface{})
if !ok {
return nil, fmt.Errorf("failed to parse response: data field is not an array")
}
models := make([]DSModel, 0, len(dataSlice))
for _, model := range dataSlice {
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/entity/models/jina.go` at line 358, The allocation of models uses an
unchecked type assertion result["data"].([]interface{}) which can panic; first
extract and check the type like data, ok := result["data"].([]interface{}) (and
treat nil as empty) and then preallocate models using len(data) only when ok is
true, otherwise set models = make([]DSModel, 0) and handle the malformed/nil
case (e.g., log or return an error) so DSModel slice creation never panics.

modelMap := model.(map[string]interface{})
modelName := modelMap["name"].(string)
models = append(models, ListModelResponse{Name: modelName})
modelName := model.(map[string]interface{})["name"].(string)

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

Nested type assertions will panic if model entry is malformed.

Line 360 chains three unchecked type assertions: model.(map[string]interface{})["name"].(string). If the upstream model entry is not a map, or the "name" key is missing, or the value is not a string, this will panic.

Use safe type assertions with ok checks and skip malformed entries or return a descriptive error.

🛡️ Proposed fix with safe nested type assertions
 	for _, model := range dataSlice {
-		modelName := model.(map[string]interface{})["name"].(string)
-		models = append(models, DSModel{
-			ID:      modelName,
-			OwnedBy: "",
-		})
+		modelMap, ok := model.(map[string]interface{})
+		if !ok {
+			continue
+		}
+		modelName, ok := modelMap["name"].(string)
+		if !ok || modelName == "" {
+			continue
+		}
+		models = append(models, DSModel{
+			ID:      modelName,
+			OwnedBy: "",
+		})
 	}
📝 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
modelName := model.(map[string]interface{})["name"].(string)
for _, model := range dataSlice {
modelMap, ok := model.(map[string]interface{})
if !ok {
continue
}
modelName, ok := modelMap["name"].(string)
if !ok || modelName == "" {
continue
}
models = append(models, DSModel{
ID: modelName,
OwnedBy: "",
})
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/entity/models/jina.go` at line 360, The direct chained assertion
model.(map[string]interface{})["name"].(string) can panic; update the code
around the modelName assignment to perform safe type checks: first assert model
is a map[string]interface{} (e.g., m, ok := model.(map[string]interface{})),
then check the "name" key exists (val, ok := m["name"]) and that val is a string
(s, ok := val.(string)); if any check fails, either skip the malformed entry or
return a descriptive error (include the offending value/context) instead of
allowing a panic, and use the validated string (s) as modelName. Ensure you
modify the surrounding logic that consumes modelName to handle the skip/error
path accordingly.

}
}
return models, nil
return ParseListModel(ModelList{Models: result.Data}), 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

🏁 Script executed:

#!/bin/bash
# Description: Verify ParseListModel implementation for empty-ID handling

# Locate and display ParseListModel implementation
ast-grep --pattern $'func ParseListModel($$$) $$$ListModelResponse {
  $$$
}'

Repository: infiniflow/ragflow

Length of output: 44


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# 1) Locate ParseListModel
echo "== Files defining ParseListModel =="
rg -n --hidden --no-ignore-vcs "func\s+ParseListModel" internal/entity/models || true

# 2) Show likely implementation (base_model.go)
echo
echo "== ParseListModel body (base_model.go) =="
BASE="internal/entity/models/base_model.go"
if [ -f "$BASE" ]; then
  # print around the function
  start=$(rg -n "func\s+ParseListModel" "$BASE" | head -n1 | cut -d: -f1 || true)
  if [ -n "${start:-}" ]; then
    # show next ~140 lines after start
    line="$start"
    end=$((line+170))
    sed -n "${line},${end}p" "$BASE" | cat -n
  else
    echo "No ParseListModel found in $BASE"
  fi
else
  echo "File not found: $BASE"
fi

# 3) Also find any usages that pass model.ID through
echo
echo "== Usages of ParseListModel =="
rg -n --hidden --no-ignore-vcs "ParseListModel\s*\(" internal/entity/models | head -n 50 || true

Repository: infiniflow/ragflow

Length of output: 5307


🏁 Script executed:

#!/bin/bash
set -euo pipefail

GOOGLE="internal/entity/models/google.go"
echo "== google.go (around lines 1-120) =="
if [ -f "$GOOGLE" ]; then
  sed -n '1,140p' "$GOOGLE" | cat -n
else
  echo "File not found: $GOOGLE"
fi

# Find where DSModel/ModelList entries are constructed and any filtering on empty IDs/names.
echo
echo "== google.go: filter checks involving empty/trim == "
rg -n "TrimSpace\(|strings\.|== \"\"|!= \"\"|empty" "$GOOGLE" || true

Repository: infiniflow/ragflow

Length of output: 6116


🏁 Script executed:

#!/bin/bash
set -euo pipefail
BASE="internal/entity/models/base_model.go"
echo "== base_model.go imports =="
# print top ~60 lines
sed -n '1,90p' "$BASE" | cat -n

Repository: infiniflow/ragflow

Length of output: 3175


🏁 Script executed:

#!/bin/bash
set -euo pipefail
BASE="internal/entity/models/base_model.go"
start=$(rg -n "func\s+ParseListModel" "$BASE" | head -n1 | cut -d: -f1)
end=$((start+80))
sed -n "${start},${end}p" "$BASE" | cat -n

Repository: infiniflow/ragflow

Length of output: 969


Guard against empty/whitespace model.ID in ParseListModel

internal/entity/models/base_model.go’s ParseListModel loops through modelList.Models, sets modelName := model.ID, optionally rewrites it to model.ID + "@" + model.OwnedBy, then unconditionally sets modelResponse.Name = modelName and appends—there’s no check to skip empty IDs. If an upstream API returns {"data":[{"id":""}]}, the list can contain entries with Name == "" (or "@<OwnedBy>" when OwnedBy is set), corrupting the model list (e.g., internal/entity/models/longcat.go: return ParseListModel(ModelList{Models: result.Data}), nil).

Add if strings.TrimSpace(model.ID) == "" { continue } before building/appending the response.

internal/entity/models/google.go is unaffected because it filters out empty trimmed names before creating DSModel entries.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/entity/models/longcat.go` at line 401, ParseListModel currently
appends entries even when model.ID is empty/whitespace; update ParseListModel
(the function handling ModelList and modelResponse.Name) to skip such entries by
adding a guard like if strings.TrimSpace(model.ID) == "" { continue } before
constructing modelName and appending to the response slice so empty IDs (or
"`@OwnedBy`" cases) are not included in the returned ModelList; ensure you import
strings if not already.

Comment on lines +547 to 567
pm := GetProviderManager()
for _, model := range result.Results {
if model.Owner != "" && model.Name != "" {
models = append(models, ListModelResponse{Name: model.Owner + "/" + model.Name})
modelName := model.Name
var modelResponse ListModelResponse
var modelEntity *Model
if pm != nil {
modelEntity = pm.GetModelByNameOrAlias(modelName)
}
if model.Owner != "" {
modelName = model.Name + "@" + model.Owner
}
modelResponse.Name = modelName
if modelEntity != nil {
modelResponse.Dimension = modelEntity.Dimension
modelResponse.MaxTokens = modelEntity.MaxTokens
modelResponse.ModelTypes = modelEntity.ModelTypes
modelResponse.Thinking = modelEntity.Thinking
}

models = append(models, modelResponse)
}

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 | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Verify the expected test assertion in replicate_test.go.

rg -n -A2 -B2 'meta/meta-llama-3-70b-instruct,replicate/hello-world' --glob 'replicate_test.go'

Repository: infiniflow/ragflow

Length of output: 451


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Show the relevant test and helper usage
rg -n --glob 'replicate_test.go' 'joinModelNames\(|ListModels\(' internal/entity/models/replicate_test.go
echo "---- replicate_test.go:250-340 ----"
sed -n '250,340p' internal/entity/models/replicate_test.go

# Locate joinModelNames definition
rg -n --glob '*.go' 'func joinModelNames\(' -S internal/entity/models
echo "---- joinModelNames definition ----"
rg -n --glob '*.go' 'func joinModelNames\(' -S internal/entity/models -n --json | head -n 20

# Show ListModels formatting around the mentioned lines
sed -n '520,590p' internal/entity/models/replicate.go

# Search for any other expectations using owner/name vs name@owner in tests
rg -n --glob 'replicate_test.go' '"meta/meta-llama-3-70b-instruct,replicate/hello-world"|name@owner|`@replicate`|`@meta`' internal/entity/models/replicate_test.go

Repository: infiniflow/ragflow

Length of output: 6286


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "---- joinModelNames ----"
sed -n '1,120p' internal/entity/models/model_test.go

echo "---- replicateModelsResponse types (replicate.go) ----"
rg -n --glob 'replicate.go' 'type replicate.*Models.*Response|replicateModelsResponse|ListModelResponse' internal/entity/models/replicate.go
sed -n '430,620p' internal/entity/models/replicate.go

echo "---- any validation/guards for model.Name in replicate.go ----"
rg -n 'model\.Name|owner.*name|GetModelByNameOrAlias|model name' internal/entity/models/replicate.go

Repository: infiniflow/ragflow

Length of output: 10286


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "---- replicateModelsResponse struct ----"
sed -n '60,120p' internal/entity/models/replicate.go

echo "---- ListModelResponse definition ----"
rg -n --glob '*.go' 'type ListModelResponse' internal/entity/models | head
# print the struct around the match
file=$(rg -n --glob '*.go' 'type ListModelResponse' internal/entity/models -l | head -n1)
line=$(rg -n --glob '*.go' 'type ListModelResponse' internal/entity/models -n | head -n1 | cut -d: -f1)
echo "file=$file line=$line"
sed -n "$((line-10)),$((line+40))p" "$file"

echo "---- Any other ListModels implementations (format differences) ----"
rg -n --glob '*/models/*.go' 'ListModels\(' internal/entity/models | head -n 50

Repository: infiniflow/ragflow

Length of output: 2005


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "---- ListModelResponse definition ----"
sed -n '60,120p' internal/entity/models/types.go

echo "---- any parsing/contract for modelName format ----"
rg -n --glob '*.go' 'Parse.*ListModel|joinModelNames|GetModelByNameOrAlias|owner/name|name@owner|`@owner`' internal/entity/models

echo "---- ListModels implementations in other drivers (name format) ----"
rg -n --glob '*.go' 'func \(r \*.*\) ListModels\(' internal/entity/models

# Show other drivers' formatting logic around modelResponse.Name where it includes '@' or '/'
rg -n --glob '*models*.go' 'modelResponse\.Name\s*=' internal/entity/models | head -n 50

Repository: infiniflow/ragflow

Length of output: 9268


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "---- ParseListModel (internal/entity/models/base_model.go) ----"
sed -n '60,140p' internal/entity/models/base_model.go

echo "---- DSModel definition (internal/entity/models/base_model.go or related) ----"
rg -n --glob '*.go' 'type DSModel' internal/entity/models | head
file=$(rg -n --glob '*.go' 'type DSModel' internal/entity/models -l | head -n1)
line=$(rg -n --glob '*.go' 'type DSModel' internal/entity/models | head -n1 | cut -d: -f1)
sed -n "$((line-10)),$((line+60))p" "$file"

echo "---- Replicate model name validation sites (replicate.go around errors) ----"
sed -n '650,720p' internal/entity/models/replicate.go
sed -n '740,820p' internal/entity/models/replicate.go

Repository: infiniflow/ragflow

Length of output: 1581


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "---- DSModel definition (internal/entity/models/deepseek.go) ----"
sed -n '420,520p' internal/entity/models/deepseek.go

echo "---- GetModelByNameOrAlias (internal/entity/models/model.go) ----"
rg -n 'func \(pm \*ProviderManager\) GetModelByNameOrAlias' internal/entity/models/model.go
sed -n '360,460p' internal/entity/models/model.go

echo "---- any normalization of modelName in provider manager ----"
rg -n 'strings\.Contains\(|Split\(|OwnedBy|@|owner/name' internal/entity/models/model.go

echo "---- replicate.go: model-name validation sites around reported errors ----"
sed -n '650,720p' internal/entity/models/replicate.go
sed -n '740,820p' internal/entity/models/replicate.go

echo "---- replicate.go: any parsing that assumes owner/name or '@' ----"
rg -n 'official model name must be owner/name|parts := strings\.Split|@' internal/entity/models/replicate.go

Repository: infiniflow/ragflow

Length of output: 6068


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "---- replicate.go: find predictionEndpoint usage ----"
rg -n --glob 'replicate.go' 'predictionEndpoint\(' internal/entity/models/replicate.go
echo "---- replicate.go: inspect around those calls ----"
# Print a window around each match line number
rg -n --glob 'replicate.go' 'predictionEndpoint\(' internal/entity/models/replicate.go | head -n 20 | cut -d: -f1 | while read -r ln; do
  start=$((ln-25)); end=$((ln+25));
  echo "== around replicate.go:$ln ==";
  sed -n "${start},${end}p" internal/entity/models/replicate.go;
done

Repository: infiniflow/ragflow

Length of output: 8328


Fix ListModels name formatting vs replicate_test.go, and guard against empty model.Name.

  • internal/entity/models/replicate.go formats ListModelResponse.Name as model.Name + "@" + model.Owner (when Owner != ""), but internal/entity/models/replicate_test.go expects owner/name (e.g., meta/meta-llama-3-70b-instruct), so the test assertion is incompatible with the current behavior.
  • ListModels appends modelResponse.Name even when model.Name is empty, producing malformed entries like @replicate or ""; validate/skip empty model.Name before appending.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/entity/models/replicate.go` around lines 547 - 567, The loop in
replicate.go currently formats ListModelResponse.Name as "name@owner" and can
append entries when model.Name is empty; change the formatting to "owner/name"
when model.Owner is non-empty (i.e., set modelResponse.Name = model.Owner + "/"
+ model.Name) to match replicate_test.go expectations, and add a guard to skip
any result where model.Name is empty before constructing modelResponse and
appending to models; keep existing enrichment from pm.GetModelByNameOrAlias
(modelEntity) intact when present.

Comment on lines 548 to 567
for _, model := range result.Results {
if model.Owner != "" && model.Name != "" {
models = append(models, ListModelResponse{Name: model.Owner + "/" + model.Name})
modelName := model.Name
var modelResponse ListModelResponse
var modelEntity *Model
if pm != nil {
modelEntity = pm.GetModelByNameOrAlias(modelName)
}
if model.Owner != "" {
modelName = model.Name + "@" + model.Owner
}
modelResponse.Name = modelName
if modelEntity != nil {
modelResponse.Dimension = modelEntity.Dimension
modelResponse.MaxTokens = modelEntity.MaxTokens
modelResponse.ModelTypes = modelEntity.ModelTypes
modelResponse.Thinking = modelEntity.Thinking
}

models = append(models, modelResponse)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Validate that model.Name is non-empty before constructing the response.

If model.Name is empty and model.Owner is present, line 556 produces a malformed name like "@owner". If both are empty, modelResponse.Name becomes an empty string. The code should skip models with empty Name fields to avoid polluting the output.

🛡️ Proposed fix to skip models with empty names
 	for _, model := range result.Results {
+		if strings.TrimSpace(model.Name) == "" {
+			continue
+		}
 		modelName := model.Name
📝 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
for _, model := range result.Results {
if model.Owner != "" && model.Name != "" {
models = append(models, ListModelResponse{Name: model.Owner + "/" + model.Name})
modelName := model.Name
var modelResponse ListModelResponse
var modelEntity *Model
if pm != nil {
modelEntity = pm.GetModelByNameOrAlias(modelName)
}
if model.Owner != "" {
modelName = model.Name + "@" + model.Owner
}
modelResponse.Name = modelName
if modelEntity != nil {
modelResponse.Dimension = modelEntity.Dimension
modelResponse.MaxTokens = modelEntity.MaxTokens
modelResponse.ModelTypes = modelEntity.ModelTypes
modelResponse.Thinking = modelEntity.Thinking
}
models = append(models, modelResponse)
}
for _, model := range result.Results {
if strings.TrimSpace(model.Name) == "" {
continue
}
modelName := model.Name
var modelResponse ListModelResponse
var modelEntity *Model
if pm != nil {
modelEntity = pm.GetModelByNameOrAlias(modelName)
}
if model.Owner != "" {
modelName = model.Name + "@" + model.Owner
}
modelResponse.Name = modelName
if modelEntity != nil {
modelResponse.Dimension = modelEntity.Dimension
modelResponse.MaxTokens = modelEntity.MaxTokens
modelResponse.ModelTypes = modelEntity.ModelTypes
modelResponse.Thinking = modelEntity.Thinking
}
models = append(models, modelResponse)
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/entity/models/replicate.go` around lines 548 - 567, The loop over
result.Results must skip entries with empty model.Name to avoid producing names
like "`@owner`" or empty Name fields; inside the for loop (where modelName :=
model.Name and modelResponse.Name is set) add a guard that if model.Name is
empty (after trimming) then continue, ensuring you do not call
pm.GetModelByNameOrAlias or construct a ListModelResponse for that item; keep
existing logic for combining model.Name and model.Owner and populating fields
from modelEntity (from pm.GetModelByNameOrAlias) unchanged for valid names.

Comment on lines +355 to +360
var result []DSModel
if err = json.Unmarshal(body, &result); err != nil {
return nil, fmt.Errorf("failed to parse response: %w", err)
}

models := make([]ListModelResponse, 0, len(result))
for _, model := range result {
if model.ID != "" {
models = append(models, ListModelResponse{Name: model.ID})
}
}
return models, nil
return ParseListModel(ModelList{Models: result}), 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 | ⚡ Quick win

Empty-ID filter removed; behavioral change may introduce empty model names.

The prior implementation filtered out models with empty IDs before building the response. The new code unmarshals directly into []DSModel and delegates to ParseListModel without filtering. ParseListModel does not skip models with empty ID fields, so if the upstream API returns any model with an empty id, it will now appear in the output with Name: "" (or Name: "@ownedby" if OwnedBy is set).

Restore the empty-ID filter to preserve the original behavior.

♻️ Proposed fix to restore the filter
 	var result []DSModel
 	if err = json.Unmarshal(body, &result); err != nil {
 		return nil, fmt.Errorf("failed to parse response: %w", err)
 	}
 
+	// Filter out models with empty IDs
+	filtered := make([]DSModel, 0, len(result))
+	for _, model := range result {
+		if model.ID != "" {
+			filtered = append(filtered, model)
+		}
+	}
+
-	return ParseListModel(ModelList{Models: result}), nil
+	return ParseListModel(ModelList{Models: filtered}), nil
📝 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
var result []DSModel
if err = json.Unmarshal(body, &result); err != nil {
return nil, fmt.Errorf("failed to parse response: %w", err)
}
models := make([]ListModelResponse, 0, len(result))
for _, model := range result {
if model.ID != "" {
models = append(models, ListModelResponse{Name: model.ID})
}
}
return models, nil
return ParseListModel(ModelList{Models: result}), nil
var result []DSModel
if err = json.Unmarshal(body, &result); err != nil {
return nil, fmt.Errorf("failed to parse response: %w", err)
}
// Filter out models with empty IDs
filtered := make([]DSModel, 0, len(result))
for _, model := range result {
if model.ID != "" {
filtered = append(filtered, model)
}
}
return ParseListModel(ModelList{Models: filtered}), nil
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/entity/models/togetherai.go` around lines 355 - 360, The change
removed filtering of DSModel entries with empty ID, causing models with empty
Name to surface; fix by filtering the unmarshaled result slice (variable result
of type []DSModel) to exclude any DSModel where ID == "" before constructing
ModelList and calling ParseListModel(ModelList{Models: filtered}). Ensure you
perform the filter right after json.Unmarshal and pass the filtered slice (not
the original result) into ParseListModel.

@Haruko386 Haruko386 mentioned this pull request Jun 11, 2026
2 of 6 tasks
@JinHai-CN
JinHai-CN merged commit 84edf53 into infiniflow:main Jun 11, 2026
2 checks passed
Lobster-0429 added a commit to Lobster-0429/ragflow that referenced this pull request Jun 11, 2026
Resolve the base_model.go conflict by keeping both new functions: this PR's
ParseSSEStream helper and ParseListModel added on main by the infiniflow#15900 list-models
refactor.

Also fix a pre-existing main typo surfaced by the merge — gitee_test.go
referenced the undefined DSModelList; corrected to ModelList, its actual type
after the infiniflow#15900 rename.
JinHai-CN pushed a commit that referenced this pull request Jun 17, 2026
### What problem does this PR solve?

Part of #15853 (provider model-list refactor). Final two providers.

- **voyage:** Voyage AI exposes no live model-list endpoint — its public
API only has `/v1/embeddings` and `/v1/rerank` — so the previous
`ListModels` was a `no such method` stub. Replace it with a
static-catalog listing sourced from the loaded provider definition,
carrying each model's `max_tokens`, `model_types`, and embedding
`dimensions`. `list models from voyage` now returns the 13-model catalog
instead of erroring.
- **fishaudio:** route the existing `/model` voice listing through the
shared `ParseListModel` helper for consistency; keep the human-readable
`title` as the model name and fall back to `_id` when a title is blank.

#### Drive-by fix
Shared gitee_test.go `DSModelList` -> `ModelList` compile fix (renamed
in #15900); auto-resolves against the sibling #15853 PRs.

### Type of change

- [x] New Feature (non-breaking change which adds functionality)
- [x] Refactoring

Co-authored-by: Haruko386 <[email protected]>
JinHai-CN pushed a commit that referenced this pull request Jun 17, 2026
…ListModel (#15853) (#15955)

### What problem does this PR solve?

Part of #15853 (provider model-list refactor).

Refactors **Ollama** `ListModels` onto the shared `ParseListModel`
pattern and fixes two correctness issues:

- **Endpoint:** switch the models suffix from `api/ps` (only
currently-running models) to `api/tags` (all installed models) — the
latter is what a model picker should show.
- **Parsing:** Ollama returns `{"models":[{"name","model"}]}`, a
non-OpenAI shape. Decode it into a typed struct, map the names into
`ModelList`, then enrich through `ParseListModel`. This removes the
previous unchecked type assertions (`result["models"].([]interface{})` /
`.(map[string]interface{})` / `.(string)`) that **panicked** when the
body was missing the `models` array or any field, and adds a fallback to
the `model` field when `name` is blank.
- Drops the no-op GET request body and a dead base-URL reassignment.

#### Drive-by fix
Shared gitee_test.go `DSModelList` -> `ModelList` compile fix (renamed
in #15900) so the models test package builds; auto-resolves against the
sibling #15853 PRs.

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
- [x] Refactoring
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants