Skip to content

feat(go-cli): support batch model add/remove and optional embedding dimension - #15631

Merged
xugangqiang merged 3 commits into
infiniflow:mainfrom
Harry-Hz-Zhang:add-models-cli
Jun 5, 2026
Merged

xugangqiang merged 3 commits into
infiniflow:mainfrom
Harry-Hz-Zhang:add-models-cli

Conversation

@Harry-Hz-Zhang

@Harry-Hz-Zhang Harry-Hz-Zhang commented Jun 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This PR improves the Go CLI in two areas:

  1. It adds batch model management support, allowing multiple models to be added or removed in a single command.
  2. It makes the dimension argument optional for the embed text command.

These changes keep the existing single-model and explicit-dimension behaviors compatible while making the CLI more convenient for common workflows.

What Changed

1. Batch model add/remove support

The CLI now supports operating on multiple model names provided in a single quoted string.

Supported commands include:

add model 'x1 x2 x3' to provider 'vllm' instance 'test' with tokens 1024 chat think vision, token 2048 chat, token 1024 think vision;

drop model 'x1 x2 x3' from 'vllm' 'test';

remove model 'x1 x2 x3' from 'vllm' 'test';

For add model, each config segment after with is matched to the corresponding model name by position.

Example mapping:

  • x1 -> tokens 1024, chat + vision, thinking=true
  • x2 -> tokens 2048, chat
  • x3 -> tokens 1024, vision, thinking=true

The existing single-model syntax remains supported.

2. Optional embedding dimension

Previously, the Go CLI required dimension to be explicitly provided for embed text.

Before:

embed text 'what is rag' 'who are you' with 'model@test@provider' dimension 8192;

Now both forms are supported:

embed text 'what is rag' 'who are you' with 'model@test@provider' dimension 8192;

embed text 'what is rag' 'who are you' with 'model@test@provider';

When omitted, the CLI leaves dimension unset and relies on provider/backend behavior.

Tests

Added parser tests covering:

  • Multiple models with multiple config segments
  • Model type deduplication
  • Model/config count mismatch
  • Drop/remove multiple models
  • Optional embedding dimension parsing

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

coderabbitai Bot commented Jun 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The CLI parser now accepts multiple model names in one quoted string and builds per-model configs into a models array; REMOVE/DROP MODEL accept multiple names. RAGFlowClient.AddCustomModel sends {provider_name, instance_name, models}. DIMENSION in embed parsing is optional.

Changes

Multi-model CLI command support

Layer / File(s) Summary
Model name parsing helpers
internal/cli/user_parser.go
parseModelNames splits and validates multiple whitespace-delimited model names from a single string; AddModelConfig struct added.
Multi-model command parsing
internal/cli/user_parser.go
parseAddModel rebuilt to parse multiple model names, parse per-model WITH flags and TOKENS, deduplicate types, assemble models slice, validate counts; parseRemoveCommand/parseDropInstanceModel updated to use multi-name parsing.
Backend request payload update
internal/cli/user_command.go
AddCustomModel now reads cmd.Params["models"] ([]map[string]any) and posts {provider_name, instance_name, models}; DropInstanceModel reads model_names and builds DELETE payload with models array.
Optional embed DIMENSION parsing
internal/cli/user_parser.go
parseEmbedCommand treats DIMENSION as optional, sets dimension only when >0, consumes optional semicolon, and requires EOF.

Sequence Diagram

sequenceDiagram
  participant CLI as CLI Parser
  participant Client as RAGFlowClient.AddCustomModel
  participant API as Backend API
  CLI->>Client: build cmd.Params with provider_name, instance_name, models[]
  Client->>API: POST /api/... {provider_name, instance_name, models}
  API-->>Client: 200/JSON response with Code/Duration
  Client-->>CLI: propagate response (Code, Duration, message)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

🐰 Multiple models hop in a line,
Names split and options align,
Each config bundled, tidy and small,
Sent to the backend, one request for all,
A rabbit cheers the multi-model call!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
Title check ✅ Passed The title accurately summarizes the main changes: batch model add/remove and optional embedding dimension, matching the primary objectives of the PR.
Description check ✅ Passed The PR description comprehensively covers the problem being solved, changes made, and includes examples. It addresses both major features (batch model management and optional dimension) with clear examples and expected behavior.

✏️ 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.

@Harry-Hz-Zhang Harry-Hz-Zhang added the ci Continue Integration label Jun 4, 2026
@Harry-Hz-Zhang
Harry-Hz-Zhang marked this pull request as draft June 4, 2026 04:42
@Harry-Hz-Zhang
Harry-Hz-Zhang marked this pull request as ready for review June 4, 2026 04:42

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
internal/cli/user_parser.go (1)

862-867: 💤 Low value

Unused struct AddModelConfig.

This struct is defined but never used in the implementation. The code uses map[string]any instead for building model configurations. Either remove this dead code or refactor to use the struct for better type safety.

🤖 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/cli/user_parser.go` around lines 862 - 867, The AddModelConfig
struct is dead code because the implementation builds model configuration with
map[string]any instead. Either remove AddModelConfig if it is not needed, or
refactor the relevant parsing/building path in user_parser.go to use
AddModelConfig consistently so the model config flow is type-safe and the struct
is actually referenced.
🤖 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/cli/user_command.go`:
- Around line 2684-2687: The error message is misleading: the code checks
cmd.Params["models"] into variable models but returns "model name not provided";
update the returned error to accurately reference the parameter being validated
(e.g., "models parameter not provided" or "models not provided") in the block
that performs the type assertion on cmd.Params["models"] to make the error clear
when models is missing or wrong-typed.

In `@internal/cli/user_parser.go`:
- Around line 851-856: The duplicate detection in Parse logic uses
case-sensitive keys (seen[modelName]) but the backend normalizes names with
strings.ToLower; update the dedupe to normalize model names the same way before
checking/adding to seen (e.g., use strings.ToLower(modelName) when indexing the
seen map and when reporting the duplicate error) so inputs like "GPT4" and
"gpt4" are treated as duplicates; modify the block referencing modelNames and
the seen map accordingly (preserve the original modelName for error text if
desired).

---

Nitpick comments:
In `@internal/cli/user_parser.go`:
- Around line 862-867: The AddModelConfig struct is dead code because the
implementation builds model configuration with map[string]any instead. Either
remove AddModelConfig if it is not needed, or refactor the relevant
parsing/building path in user_parser.go to use AddModelConfig consistently so
the model config flow is type-safe and the struct is actually referenced.
🪄 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: 32e349b7-089c-4599-94d3-2116e460d8d7

📥 Commits

Reviewing files that changed from the base of the PR and between 597ac1e and c234b79.

📒 Files selected for processing (2)
  • internal/cli/user_command.go
  • internal/cli/user_parser.go

Comment on lines +2684 to 2687
models, ok := cmd.Params["models"].([]map[string]any)
if !ok {
return nil, fmt.Errorf("model name not provided")
}

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

Error message does not match parameter name.

The error says "model name not provided" but the parameter being checked is models. This is misleading for debugging.

🔧 Proposed fix
 models, ok := cmd.Params["models"].([]map[string]any)
 if !ok {
-    return nil, fmt.Errorf("model name not provided")
+    return nil, fmt.Errorf("models not provided")
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
models, ok := cmd.Params["models"].([]map[string]any)
if !ok {
return nil, fmt.Errorf("model name not provided")
}
models, ok := cmd.Params["models"].([]map[string]any)
if !ok {
return nil, fmt.Errorf("models not provided")
}
🤖 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/cli/user_command.go` around lines 2684 - 2687, The error message is
misleading: the code checks cmd.Params["models"] into variable models but
returns "model name not provided"; update the returned error to accurately
reference the parameter being validated (e.g., "models parameter not provided"
or "models not provided") in the block that performs the type assertion on
cmd.Params["models"] to make the error clear when models is missing or
wrong-typed.

Comment on lines +851 to +856
seen := make(map[string]struct{}, len(modelNames))
for _, modelName := range modelNames {
if _, ok := seen[modelName]; ok {
return nil, fmt.Errorf("duplicate model name: %s", modelName)
}
seen[modelName] = struct{}{}

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

Case-sensitive duplicate detection mismatches backend validation.

The CLI uses case-sensitive comparison (seen[modelName]), but the backend at model_service.go:2025-2029 uses case-insensitive detection via strings.ToLower(modelName). This allows CLI to accept inputs like 'GPT4 gpt4' that the backend will reject as duplicates.

🔧 Proposed fix to align with backend behavior
 seen := make(map[string]struct{}, len(modelNames))
 for _, modelName := range modelNames {
-    if _, ok := seen[modelName]; ok {
+    key := strings.ToLower(modelName)
+    if _, ok := seen[key]; ok {
         return nil, fmt.Errorf("duplicate model name: %s", modelName)
     }
-    seen[modelName] = struct{}{}
+    seen[key] = 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/cli/user_parser.go` around lines 851 - 856, The duplicate detection
in Parse logic uses case-sensitive keys (seen[modelName]) but the backend
normalizes names with strings.ToLower; update the dedupe to normalize model
names the same way before checking/adding to seen (e.g., use
strings.ToLower(modelName) when indexing the seen map and when reporting the
duplicate error) so inputs like "GPT4" and "gpt4" are treated as duplicates;
modify the block referencing modelNames and the seen map accordingly (preserve
the original modelName for error text if desired).

@Harry-Hz-Zhang Harry-Hz-Zhang changed the title feat(go-cli): add models cli feat(go-cli): add models cli cmd and make embedding dimension optional in cli embed cmd Jun 4, 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.

Caution

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

⚠️ Outside diff range comments (1)
internal/cli/user_parser.go (1)

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

Misleading error message.

The error message says "expected provider name" but this code block is parsing the instance name.

🔧 Proposed fix
 	// instance name
 	if p.curToken.Type != TokenQuotedString {
-		return nil, fmt.Errorf("expected provider name")
+		return nil, fmt.Errorf("expected instance name")
 	}
🤖 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/cli/user_parser.go` around lines 912 - 915, The error message in the
instance-name parsing branch is misleading: when checking p.curToken.Type !=
TokenQuotedString (parsing the instance name) it currently returns
fmt.Errorf("expected provider name"); change the error text to reflect the
actual field (e.g., "expected instance name" or "expected quoted instance name")
so callers of the parsing function get the correct failure context; update the
error string in the block that uses p.curToken and TokenQuotedString (in
user_parser.go) accordingly.
🧹 Nitpick comments (2)
internal/cli/user_parser.go (2)

928-930: 💤 Low value

Inconsistent error message casing.

Other error messages in this file use uppercase for keywords (e.g., "expected FROM", "expected PROVIDER"). This one uses lowercase "expected with".

🔧 Proposed fix
 	if p.curToken.Type != TokenWith {
-		return nil, fmt.Errorf("expected with")
+		return nil, fmt.Errorf("expected WITH")
 	}
🤖 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/cli/user_parser.go` around lines 928 - 930, The error message for
the TokenWith check is inconsistent with other messages; update the returned
error in the block that checks p.curToken.Type != TokenWith (the TokenWith
branch) to use uppercase keyword "WITH" (e.g., "expected WITH") so it matches
the style used for "expected FROM" and "expected PROVIDER".

862-867: 💤 Low value

AddModelConfig struct appears unused.

This struct is defined but never instantiated. The parseAddModel function builds []map[string]any directly (lines 1021-1028) to satisfy the downstream contract in AddCustomModel. Consider removing this dead code or using it to improve type safety.

🤖 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/cli/user_parser.go` around lines 862 - 867, The AddModelConfig
struct is dead code; either delete it or use it to improve type safety by
modifying parseAddModel to construct []AddModelConfig (populate ModelName,
ModelTypes, MaxTokens, Thinking) instead of building []map[string]any directly,
then convert that slice to the []map[string]any expected by AddCustomModel
before calling it; update any callers or tests accordingly so references use the
new typed slice or remove the unused AddModelConfig type if you prefer the
map-based contract.
🤖 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.

Outside diff comments:
In `@internal/cli/user_parser.go`:
- Around line 912-915: The error message in the instance-name parsing branch is
misleading: when checking p.curToken.Type != TokenQuotedString (parsing the
instance name) it currently returns fmt.Errorf("expected provider name"); change
the error text to reflect the actual field (e.g., "expected instance name" or
"expected quoted instance name") so callers of the parsing function get the
correct failure context; update the error string in the block that uses
p.curToken and TokenQuotedString (in user_parser.go) accordingly.

---

Nitpick comments:
In `@internal/cli/user_parser.go`:
- Around line 928-930: The error message for the TokenWith check is inconsistent
with other messages; update the returned error in the block that checks
p.curToken.Type != TokenWith (the TokenWith branch) to use uppercase keyword
"WITH" (e.g., "expected WITH") so it matches the style used for "expected FROM"
and "expected PROVIDER".
- Around line 862-867: The AddModelConfig struct is dead code; either delete it
or use it to improve type safety by modifying parseAddModel to construct
[]AddModelConfig (populate ModelName, ModelTypes, MaxTokens, Thinking) instead
of building []map[string]any directly, then convert that slice to the
[]map[string]any expected by AddCustomModel before calling it; update any
callers or tests accordingly so references use the new typed slice or remove the
unused AddModelConfig type if you prefer the map-based contract.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 8cbf2c56-26ae-461e-ac86-f22f10cd8e82

📥 Commits

Reviewing files that changed from the base of the PR and between c234b79 and 9e8b103.

📒 Files selected for processing (1)
  • internal/cli/user_parser.go

@codecov

codecov Bot commented Jun 4, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (67c3e73) to head (3bf7671).
⚠️ Report is 9 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15631   +/-   ##
=======================================
  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.

@Harry-Hz-Zhang Harry-Hz-Zhang changed the title feat(go-cli): add models cli cmd and make embedding dimension optional in cli embed cmd feat(go-cli): support batch model add/remove and optional embedding dimension Jun 4, 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.

Caution

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

⚠️ Outside diff range comments (2)
internal/cli/user_parser.go (1)

844-859: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Whitespace splitting breaks single model names that contain spaces.

strings.Fields(raw) turns a previously valid quoted single name like 'my custom model' into three model names. That regresses both ADD MODEL and DROP/REMOVE MODEL, so the new multi-name syntax is no longer backward-compatible for any model name containing whitespace.

🤖 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/cli/user_parser.go` around lines 844 - 859, parseModelNames
currently uses strings.Fields which breaks quoted names; replace that with a
tokenization that respects quotes and preserves spaces inside quoted tokens
(e.g., iterate raw and build tokens, treating text inside single or double
quotes as a single token and allowing commas/whitespace as separators). Keep the
rest of the logic (nil/empty check and duplicate detection using seen) intact
and return the collected tokens as modelNames from parseModelNames.
internal/cli/user_command.go (1)

1871-1882: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Don't reintroduce dimension: 0 when the user omitted DIMENSION.

parseEmbedCommand() now leaves cmd.Params["dimension"] unset when the CLI uses the new no-dimension form, but this method always serializes "dimension": 0. That collapses “unset” back into an explicit value, so the new optional syntax can still override backend defaults or trip validation that distinguishes missing from zero.

Proposed fix
-	dimension, ok := cmd.Params["dimension"].(int)
-	if !ok {
-		dimension = 0
-	}
+	dimension, hasDimension := cmd.Params["dimension"].(int)

 	payload := map[string]interface{}{
 		"provider_name": providerName,
 		"instance_name": instanceName,
 		"model_name":    modelName,
 		"texts":         texts,
-		"dimension":     dimension,
 	}
+	if hasDimension {
+		payload["dimension"] = dimension
+	}
🤖 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/cli/user_command.go` around lines 1871 - 1882, The payload always
includes "dimension": 0 because the code forces a zero when
cmd.Params["dimension"] is missing; instead, preserve absence by only adding the
"dimension" key to payload when cmd.Params["dimension"] exists and is an int.
Locate the cmd.Params["dimension"] check and the payload map creation in
user_command.go (the variables dimension, ok and payload map) and change the
logic so that if ok is false you do not set "dimension" in payload (only include
it when ok is true and the value is an int).
🤖 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.

Outside diff comments:
In `@internal/cli/user_command.go`:
- Around line 1871-1882: The payload always includes "dimension": 0 because the
code forces a zero when cmd.Params["dimension"] is missing; instead, preserve
absence by only adding the "dimension" key to payload when
cmd.Params["dimension"] exists and is an int. Locate the cmd.Params["dimension"]
check and the payload map creation in user_command.go (the variables dimension,
ok and payload map) and change the logic so that if ok is false you do not set
"dimension" in payload (only include it when ok is true and the value is an
int).

In `@internal/cli/user_parser.go`:
- Around line 844-859: parseModelNames currently uses strings.Fields which
breaks quoted names; replace that with a tokenization that respects quotes and
preserves spaces inside quoted tokens (e.g., iterate raw and build tokens,
treating text inside single or double quotes as a single token and allowing
commas/whitespace as separators). Keep the rest of the logic (nil/empty check
and duplicate detection using seen) intact and return the collected tokens as
modelNames from parseModelNames.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 58b1aae1-1ccd-49de-b13a-d3cccd54d3e5

📥 Commits

Reviewing files that changed from the base of the PR and between 9e8b103 and 3bf7671.

📒 Files selected for processing (2)
  • internal/cli/user_command.go
  • internal/cli/user_parser.go

@xugangqiang

Copy link
Copy Markdown
Contributor

LGTM

@xugangqiang
xugangqiang merged commit 1deb131 into infiniflow:main Jun 5, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants