Repository navigation
Go: new CLI command, list all models and show model - #15786
Conversation
📝 WalkthroughWalkthroughAdds a global model catalog loaded from conf/all_models.json, exposes ListAllModels and ShowModel in the service layer, adds a ModelHandler and protected GET /api/v1/models/all-models route, updates CLI parsing/execution for LIST/SHOW MODEL, wires modelHandler into server startup, and refactors AddModel variable shadowing. ChangesGlobal Model Catalog Feature
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Signed-off-by: Jin Hai <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (4)
internal/service/model_service.go (1)
2426-2437: 💤 Low valueConsider case-insensitive model name matching for consistency.
Line 2432 uses exact string comparison (
model["name"] == modelName). The rest of the codebase—FindProvider(line 675–676 in model.go) andfindModel(line 685–686)—usesstrings.EqualFoldfor case-insensitive matching. Applying the same convention here would makeSHOW MODELbehavior consistent with provider/model lookups elsewhere.♻️ Suggested consistency fix
for _, model := range models { - if model["name"] == modelName { + if name, ok := model["name"].(string); ok && strings.EqualFold(name, modelName) { return model, 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/service/model_service.go` around lines 2426 - 2437, ShowModel currently uses exact comparison (model["name"] == modelName) which is inconsistent with FindProvider/findModel; change ShowModel to perform case-insensitive matching using strings.EqualFold on the model name (e.g., extract the name from model["name"] as a string and call strings.EqualFold(nameStr, modelName)). Ensure you handle the type assertion safely (check that model["name"] is a string before comparing) and add the strings import if not already present.internal/entity/model.go (1)
367-369: ⚡ Quick winPrefer returning an empty array over an error when no models are found.
Returning
fmt.Errorf("no models found")at line 368 when the catalog is empty forces callers to distinguish between operational failures and "no data" states. Standard REST practice is to return a 200 OK with an empty array[]when a query succeeds but yields no results.♻️ Suggested refactor
} - if len(modelList) == 0 { - return nil, fmt.Errorf("no models found") - } - return 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/model.go` around lines 367 - 369, The function currently returns an error when modelList is empty; change it to return an empty slice and nil error instead so callers get a successful result with no items. Replace the fmt.Errorf("no models found") return with a return of an empty slice matching the function's model type (e.g., return []Model{}, nil or return modelList, nil if modelList is already an empty slice) in the function that references modelList so callers receive [] rather than an error.internal/cli/common_command.go (2)
512-548: ⚡ Quick winConsider using query parameters instead of request body for GET request.
Line 529 sends a GET request with a JSON payload body (
pageandpage_size). While this may work, it's non-standard HTTP practice—GET requests typically use query parameters for filtering/pagination. Many HTTP clients, proxies, and servers treat GET request bodies as undefined behavior per RFC 7231.Consider refactoring to use query parameters:
endPoint := fmt.Sprintf("/all-models?page=%d&page_size=%d", page, pageSize) resp, err := c.HTTPClient.Request("GET", endPoint, "web", nil, nil)Also verify that
page=0andpage_size=0produce the expected API behavior (e.g., return all results or use server defaults) when pagination parameters are not explicitly 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/common_command.go` around lines 512 - 548, In ListAllModels, move pagination values page and pageSize out of the request body and put them into the GET URL query string (build an endpoint like "/all-models?page=<page>&page_size=<pageSize>") and call c.HTTPClient.Request with nil payload instead of sending a JSON body; keep handling of resp, error, JSON unmarshal (CommonResponse) and result checks the same, and confirm how page=0 and page_size=0 should behave with the API (omit params or rely on server defaults if needed).
550-580: ⚡ Quick winConsider using query parameters for GET request.
Line 561 sends a GET request with
model_namein the request body. As noted inListAllModels, GET requests with body payloads are non-standard. Consider using query parameters:endPoint := fmt.Sprintf("/all-models?model_name=%s", url.QueryEscape(modelName)) resp, err := c.HTTPClient.Request("GET", endPoint, "web", nil, nil)Also note that this method expects
CommonDataResponse(single model) whileListAllModelsexpectsCommonResponse(model list), yet both query the same/all-modelsendpoint. Verify that the API endpoint correctly returns different response structures based on whethermodel_nameis 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/common_command.go` around lines 550 - 580, ShowModel is sending model_name in the GET body (non-standard) and expects CommonDataResponse while ListAllModels hits the same /all-models endpoint with a different response type; change ShowModel to put model_name into the URL query (build endPoint using url.QueryEscape(modelName)) and call c.HTTPClient.Request("GET", endPoint, "web", nil, nil) so the body is nil, then keep unmarshalling into CommonDataResponse; also verify the API actually returns a single-model CommonDataResponse when model_name is present and adjust the expected response type (CommonDataResponse vs CommonResponse) accordingly in ShowModel or ListAllModels if needed.
🤖 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 25-35: The model name casing in conf/all_models.json
("minimax-m3") doesn't match conf/models/minimax.json and
conf/llm_factories.json ("MiniMax-M3"), causing ShowModel (the model lookup
path) to fail due to exact string equality; fix by either updating the name in
conf/all_models.json to "MiniMax-M3" to match the provider configs, or make the
ShowModel lookup case-insensitive (use strings.EqualFold) so model["name"]
comparisons match regardless of case—update references to the "minimax-m3" entry
and the ShowModel function accordingly.
In `@internal/entity/model.go`:
- Around line 288-307: NewProviderManager is reading a hardcoded runtime file
path ("conf/all_models.json"), which fails if the working directory changes;
change it to load models from a non-relative source by either (A) using the
embed package to embed conf/all_models.json at build time (declare a
package-level variable via //go:embed conf/all_models.json and use that data
instead of os.ReadFile) or (B) accept a file path or io.Reader argument in
NewProviderManager (e.g., add a parameter modelsJSONPath string or modelsReader
io.Reader) and use that to read/parse the JSON; update the JSON unmarshalling
code (type AllModels/var allModels) to use the embedded bytes or passed reader,
and update any callers/tests of NewProviderManager to pass the embedded data or
explicit path accordingly.
In `@internal/router/router.go`:
- Around line 378-381: The route for listing models is registered on the v1
group (v1.Group("/all-models")) which yields /api/v1/all-models but the CLI
calls /all-models; fix by moving the allModels registration out of the v1 group
into the parent authorized group (register allModels :=
authorized.Group("/all-models") and call allModels.GET("",
r.modelHandler.ListAllModels)) so the endpoint path matches the CLI, or
alternatively update the CLI to request /api/v1/all-models; ensure you modify
the registration that creates allModels and keep the handler
r.modelHandler.ListAllModels unchanged.
In `@internal/service/model_service.go`:
- Around line 2415-2424: In ListAllModels, the code slices models with
models[pageIndex*pageSize:(pageIndex+1)*pageSize] without bounds checks which
can panic; validate and clamp indices: ensure pageIndex and pageSize are
non-negative, compute start = pageIndex * pageSize and end = start + pageSize,
clamp start = min(max(start, 0), len(models)) and end = min(max(end, 0),
len(models)), if start >= len(models) return an empty slice, otherwise return
models[start:end]; keep existing behavior of returning models when pageSize <=
0.
---
Nitpick comments:
In `@internal/cli/common_command.go`:
- Around line 512-548: In ListAllModels, move pagination values page and
pageSize out of the request body and put them into the GET URL query string
(build an endpoint like "/all-models?page=<page>&page_size=<pageSize>") and call
c.HTTPClient.Request with nil payload instead of sending a JSON body; keep
handling of resp, error, JSON unmarshal (CommonResponse) and result checks the
same, and confirm how page=0 and page_size=0 should behave with the API (omit
params or rely on server defaults if needed).
- Around line 550-580: ShowModel is sending model_name in the GET body
(non-standard) and expects CommonDataResponse while ListAllModels hits the same
/all-models endpoint with a different response type; change ShowModel to put
model_name into the URL query (build endPoint using url.QueryEscape(modelName))
and call c.HTTPClient.Request("GET", endPoint, "web", nil, nil) so the body is
nil, then keep unmarshalling into CommonDataResponse; also verify the API
actually returns a single-model CommonDataResponse when model_name is present
and adjust the expected response type (CommonDataResponse vs CommonResponse)
accordingly in ShowModel or ListAllModels if needed.
In `@internal/entity/model.go`:
- Around line 367-369: The function currently returns an error when modelList is
empty; change it to return an empty slice and nil error instead so callers get a
successful result with no items. Replace the fmt.Errorf("no models found")
return with a return of an empty slice matching the function's model type (e.g.,
return []Model{}, nil or return modelList, nil if modelList is already an empty
slice) in the function that references modelList so callers receive [] rather
than an error.
In `@internal/service/model_service.go`:
- Around line 2426-2437: ShowModel currently uses exact comparison
(model["name"] == modelName) which is inconsistent with FindProvider/findModel;
change ShowModel to perform case-insensitive matching using strings.EqualFold on
the model name (e.g., extract the name from model["name"] as a string and call
strings.EqualFold(nameStr, modelName)). Ensure you handle the type assertion
safely (check that model["name"] is a string before comparing) and add the
strings import if not already present.
🪄 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: d83b83ac-bf75-4cd0-9f33-f979f12941d3
📒 Files selected for processing (9)
cmd/server_main.goconf/all_models.jsonconf/models/minimax.jsoninternal/cli/client.gointernal/cli/common_command.gointernal/cli/user_parser.gointernal/entity/model.gointernal/router/router.gointernal/service/model_service.go
| // Read the file | ||
| var data []byte | ||
| data, err = os.ReadFile("conf/all_models.json") | ||
| if err != nil { | ||
| return nil, fmt.Errorf("error reading file 'conf/all_models.json': %w", err) | ||
| } | ||
|
|
||
| // Parse JSON | ||
| type AllModels struct { | ||
| Models []Model `json:"models"` | ||
| } | ||
| var allModels AllModels | ||
| if err = json.Unmarshal(data, &allModels); err != nil { | ||
| return nil, fmt.Errorf("error parsing JSON from file 'conf/all_models.json': %w", err) | ||
| } | ||
|
|
||
| return &ProviderManager{ | ||
| Providers: providers, | ||
| AllModels: allModels.Models, | ||
| }, nil |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Verify that conf/all_models.json exists and is valid JSON
if [ -f "conf/all_models.json" ]; then
echo "✓ conf/all_models.json exists"
jq empty conf/all_models.json 2>/dev/null && echo "✓ Valid JSON" || echo "✗ Invalid JSON"
else
echo "✗ conf/all_models.json is missing"
fiRepository: infiniflow/ragflow
Length of output: 105
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Show the exact code around the referenced lines
echo "=== internal/entity/model.go (around 270-330) ==="
nl -ba internal/entity/model.go | sed -n '260,340p'
# Find all references to conf/all_models.json
echo
echo "=== References to conf/all_models.json ==="
rg -n "conf/all_models\.json" -S .
# Search for ProviderManager/NewProviderManager context (best effort)
echo
echo "=== References to NewProviderManager / ProviderManager in internal/entity/model.go ==="
rg -n "NewProviderManager|ProviderManager" internal/entity/model.goRepository: infiniflow/ragflow
Length of output: 173
🏁 Script executed:
#!/bin/bash
set -euo pipefail
FILE="internal/entity/model.go"
if [ ! -f "$FILE" ]; then
echo "Missing $FILE"
exit 1
fi
echo "=== $FILE (around 270-340) ==="
# Use cat -n to include line numbers (nl is unavailable)
cat -n "$FILE" | sed -n '270,340p'
echo
echo "=== References to conf/all_models.json ==="
rg -n "conf/all_models\.json" -S .
echo
echo "=== References to NewProviderManager / ProviderManager in $FILE ==="
rg -n "NewProviderManager|type ProviderManager|ProviderManager" "$FILE"Repository: infiniflow/ragflow
Length of output: 4208
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "=== conf/ directory (top-level) ==="
ls -la conf || true
echo
find conf -maxdepth 2 -type f -print || true
echo
echo "=== References to NewProviderManager(...) across repo ==="
rg -n "NewProviderManager\s*\(" -S .
echo
echo "=== internal/entity/model.go: function header + nearby code for NewProviderManager ==="
# Print a larger chunk around function definition using sed range
cat -n internal/entity/model.go | sed -n '150,340p'Repository: infiniflow/ragflow
Length of output: 10439
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "=== internal/dao/database.go (around 130-220) ==="
cat -n internal/dao/database.go | sed -n '130,220p'
echo
echo "=== References to os.ReadFile(\"conf/\" in repo ==="
rg -n "os\.ReadFile\(\s*\"conf/" -S .
echo
echo "=== References to \"conf/\" paths in repo (high signal) ==="
rg -n "\"conf/[^\"\\n]+\"" -S internal | head -n 50Repository: infiniflow/ragflow
Length of output: 4225
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "=== internal/service/user.go around 620-700 ==="
cat -n internal/service/user.go | sed -n '620,700p'
echo
echo "=== internal/admin/password.go around 160-240 ==="
cat -n internal/admin/password.go | sed -n '160,240p'
echo
echo "=== internal/engine/elasticsearch/chunk.go references to conf/skill_es_mapping.json (around 1860-1910) ==="
cat -n internal/engine/elasticsearch/chunk.go | sed -n '1860,1910p'Repository: infiniflow/ragflow
Length of output: 7866
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "=== internal/entity/model_test.go (relevant parts) ==="
rg -n "NewProviderManager\(" internal/entity/model_test.go
echo
cat -n internal/entity/model_test.go | sed -n '1,120p'
echo
cat -n internal/entity/model_test.go | sed -n '120,260p'
echo
cat -n internal/entity/model_test.go | sed -n '260,360p'Repository: infiniflow/ragflow
Length of output: 13307
Fix hardcoded relative dependency for conf/all_models.json
conf/all_models.json is present in the repo and contains valid JSON, so the “missing/malformed in-repo” concern doesn’t apply. However, NewProviderManager still hardcodes a relative runtime path (os.ReadFile("conf/all_models.json")) and will log.Fatal on any read/parse failure, so startup can break if the working directory at runtime isn’t the repo root or if conf/ isn’t deployed alongside the binary.
🤖 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/model.go` around lines 288 - 307, NewProviderManager is
reading a hardcoded runtime file path ("conf/all_models.json"), which fails if
the working directory changes; change it to load models from a non-relative
source by either (A) using the embed package to embed conf/all_models.json at
build time (declare a package-level variable via //go:embed conf/all_models.json
and use that data instead of os.ReadFile) or (B) accept a file path or io.Reader
argument in NewProviderManager (e.g., add a parameter modelsJSONPath string or
modelsReader io.Reader) and use that to read/parse the JSON; update the JSON
unmarshalling code (type AllModels/var allModels) to use the embedded bytes or
passed reader, and update any callers/tests of NewProviderManager to pass the
embedded data or explicit path accordingly.
| allModels := v1.Group("/all-models") | ||
| { | ||
| allModels.GET("", r.modelHandler.ListAllModels) | ||
| } |
There was a problem hiding this comment.
Path mismatch: endpoint registered at /api/v1/all-models but CLI expects /all-models.
The new route is registered under the v1 group (line 179: /api/v1) as /all-models, yielding the full path /api/v1/all-models. However, the CLI client in internal/cli/common_command.go:516 requests GET /all-models directly. This mismatch will cause all CLI LIST MODELS commands to return 404. Either:
- Change line 378 to register outside the
v1group (underauthorizeddirectly), or - Update the CLI to call
/api/v1/all-models
🔧 Option 1: Move endpoint outside v1 group
model := v1.Group("/models")
{
model.GET("/", r.tenantHandler.GetModels)
model.PATCH("/", r.tenantHandler.SetModels)
}
- allModels := v1.Group("/all-models")
+ }
+
+ // Global model catalog (no /api/v1 prefix to match CLI expectation)
+ allModels := authorized.Group("/all-models")
+ {
- {
allModels.GET("", r.modelHandler.ListAllModels)
- }
+ }
+ v1 := authorized.Group("/api/v1")
+ {
// Agent routes🔧 Option 2: Update CLI to use /api/v1/all-models
In internal/cli/common_command.go:
- resp, err := c.HTTPClient.Request("GET", "/all-models", "web", nil, payload)
+ resp, err := c.HTTPClient.Request("GET", "/api/v1/all-models", "web", nil, payload)🤖 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/router/router.go` around lines 378 - 381, The route for listing
models is registered on the v1 group (v1.Group("/all-models")) which yields
/api/v1/all-models but the CLI calls /all-models; fix by moving the allModels
registration out of the v1 group into the parent authorized group (register
allModels := authorized.Group("/all-models") and call allModels.GET("",
r.modelHandler.ListAllModels)) so the endpoint path matches the CLI, or
alternatively update the CLI to request /api/v1/all-models; ensure you modify
the registration that creates allModels and keep the handler
r.modelHandler.ListAllModels unchanged.
| func (m *ModelProviderService) ListAllModels(pageIndex, pageSize int) ([]map[string]interface{}, error) { | ||
| models, err := dao.GetModelProviderManager().ListAllModels() | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| if pageSize > 0 { | ||
| return models[pageIndex*pageSize : (pageIndex+1)*pageSize], nil | ||
| } | ||
| return models, nil | ||
| } |
There was a problem hiding this comment.
Add bounds checking before slicing the models array.
Lines 2420–2421 perform unchecked slice operations: models[pageIndex*pageSize : (pageIndex+1)*pageSize]. If pageIndex or pageSize are out of range, this will panic at runtime. Validate inputs and clamp the slice indices to prevent crashes.
🛡️ Proposed bounds checking
func (m *ModelProviderService) ListAllModels(pageIndex, pageSize int) ([]map[string]interface{}, error) {
models, err := dao.GetModelProviderManager().ListAllModels()
if err != nil {
return nil, err
}
- if pageSize > 0 {
- return models[pageIndex*pageSize : (pageIndex+1)*pageSize], nil
+ if pageSize > 0 && pageIndex >= 0 {
+ start := pageIndex * pageSize
+ end := start + pageSize
+ if start >= len(models) {
+ return []map[string]interface{}{}, nil
+ }
+ if end > len(models) {
+ end = len(models)
+ }
+ return models[start:end], nil
}
return models, 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.
| func (m *ModelProviderService) ListAllModels(pageIndex, pageSize int) ([]map[string]interface{}, error) { | |
| models, err := dao.GetModelProviderManager().ListAllModels() | |
| if err != nil { | |
| return nil, err | |
| } | |
| if pageSize > 0 { | |
| return models[pageIndex*pageSize : (pageIndex+1)*pageSize], nil | |
| } | |
| return models, nil | |
| } | |
| func (m *ModelProviderService) ListAllModels(pageIndex, pageSize int) ([]map[string]interface{}, error) { | |
| models, err := dao.GetModelProviderManager().ListAllModels() | |
| if err != nil { | |
| return nil, err | |
| } | |
| if pageSize > 0 && pageIndex >= 0 { | |
| start := pageIndex * pageSize | |
| end := start + pageSize | |
| if start >= len(models) { | |
| return []map[string]interface{}{}, nil | |
| } | |
| if end > len(models) { | |
| end = len(models) | |
| } | |
| return models[start:end], nil | |
| } | |
| return models, 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/service/model_service.go` around lines 2415 - 2424, In
ListAllModels, the code slices models with
models[pageIndex*pageSize:(pageIndex+1)*pageSize] without bounds checks which
can panic; validate and clamp indices: ensure pageIndex and pageSize are
non-negative, compute start = pageIndex * pageSize and end = start + pageSize,
clamp start = min(max(start, 0), len(models)) and end = min(max(end, 0),
len(models)), if start >= len(models) return an empty slice, otherwise return
models[start:end]; keep existing behavior of returning models when pageSize <=
0.
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (1)
internal/handler/models.go (1)
45-98: ⚖️ Poor tradeoffConsider splitting list and show operations into separate handler methods.
The method
ListAllModelshandles two distinct operations based on the presence ofModelNamein the request body. This couples two responsibilities in one handler and makes the API less discoverable.Consider refactoring into separate methods and routes:
ListAllModelsfor listing (POST /api/v1/models/all-models with pagination in body)ShowModelfor single model (GET /api/v1/models/all-models/:name)Or keep one endpoint but rename the method to better reflect its dual purpose (e.g.,
HandleModelsQuery).🤖 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/handler/models.go` around lines 45 - 98, The ListAllModels handler currently does two jobs (list vs. show) based on req.ModelName; split responsibilities by creating two handlers: keep ListAllModels to only handle pagination listing (remove the req.ModelName branch, bind a pagination request struct, call h.modelProviderService.ListAllModels(page, pageSize) and return models), and add a new ShowModel handler that reads the model name from the URL (e.g., path param), calls h.modelProviderService.ShowModel(name) and returns the single model; update routing to expose POST /api/v1/models/all-models (ListAllModels) and GET /api/v1/models/all-models/:name (ShowModel) or, if you prefer a single endpoint, rename ListAllModels to HandleModelsQuery and keep the existing conditional logic — ensure you update request binding and remove the mixed logic from ListAllModels so each handler has a single responsibility.
🤖 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/handler/models.go`:
- Line 27: Update the incorrect doc comments that refer to "ProviderHandler" so
they match the actual type name "ModelHandler": change any comment above the
ModelHandler struct and its related constructor/factory function (e.g.,
NewModelHandler or similar) to reference ModelHandler instead of
ProviderHandler, ensuring the comment text and any // ProviderHandler or
ProviderHandler... occurrences are replaced with // ModelHandler and mention the
correct symbol names.
- Line 49: Remove the debug println call that uses printf-style formatting
(println("JSON bind error: %v (type: %T)", err, err)) and replace it with a
structured log call using your project's logger (e.g., processLogger, logger, or
standard log) so the error and its type are recorded properly; reference the
existing error variable err and ensure the message is descriptive (e.g., "JSON
bind error") while passing err as structured context instead of using println.
- Around line 59-60: Validate and sanitize pagination before calling the
service: ensure req.Page and req.PageSize are positive integers (e.g., default
to 1 and a sane max like 100 if zero/negative or out-of-range) and compute
pageIndex = page - 1 only after validation; if values are invalid return a 4xx
error instead of forwarding them. In short, check req.Page and req.PageSize
(variables page and pageSize in the handler), enforce page >= 1 and pageSize > 0
(and optionally cap pageSize), and only call the service method that slices
models with these validated values to prevent the slice bounds panic.
- Around line 50-54: Handlers in internal/handler/models.go currently always
return http.StatusOK for errors (using c.JSON(http.StatusOK,...)) which is
inconsistent with connector.go; pick a single convention—prefer using proper
HTTP status codes—and update the error responses in models.go to return the
matching 4xx/5xx status (e.g., http.StatusBadRequest or
http.StatusInternalServerError) when sending JSON with
common.CodeBadRequest/common.CodeInternalError, update the c.JSON(...) calls
(the ones that currently pass http.StatusOK) to the appropriate http status, and
ensure the same convention is applied across internal/handler/llm.go and
internal/handler/connector.go for consistency.
---
Nitpick comments:
In `@internal/handler/models.go`:
- Around line 45-98: The ListAllModels handler currently does two jobs (list vs.
show) based on req.ModelName; split responsibilities by creating two handlers:
keep ListAllModels to only handle pagination listing (remove the req.ModelName
branch, bind a pagination request struct, call
h.modelProviderService.ListAllModels(page, pageSize) and return models), and add
a new ShowModel handler that reads the model name from the URL (e.g., path
param), calls h.modelProviderService.ShowModel(name) and returns the single
model; update routing to expose POST /api/v1/models/all-models (ListAllModels)
and GET /api/v1/models/all-models/:name (ShowModel) or, if you prefer a single
endpoint, rename ListAllModels to HandleModelsQuery and keep the existing
conditional logic — ensure you update request binding and remove the mixed logic
from ListAllModels so each handler has a single responsibility.
🪄 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: c292bc99-6f59-4e9b-8952-08435045b1e4
📒 Files selected for processing (1)
internal/handler/models.go
| "github.com/gin-gonic/gin" | ||
| ) | ||
|
|
||
| // ProviderHandler provider handler |
There was a problem hiding this comment.
Fix documentation comments to match actual type names.
Lines 27 and 32 reference "ProviderHandler" but the actual type is ModelHandler. Update the comments to match the struct and function names.
📝 Proposed fix
-// ProviderHandler provider handler
+// ModelHandler model handler
type ModelHandler struct {
modelProviderService *service.ModelProviderService
}
-// NewProviderHandler create provider handler
+// NewModelHandler create model handler
func NewModelHandler(modelProviderService *service.ModelProviderService) *ModelHandler {Also applies to: 32-32
🤖 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/handler/models.go` at line 27, Update the incorrect doc comments
that refer to "ProviderHandler" so they match the actual type name
"ModelHandler": change any comment above the ModelHandler struct and its related
constructor/factory function (e.g., NewModelHandler or similar) to reference
ModelHandler instead of ProviderHandler, ensuring the comment text and any //
ProviderHandler or ProviderHandler... occurrences are replaced with //
ModelHandler and mention the correct symbol names.
|
|
||
| var req ShowModelRequest | ||
| if err := c.ShouldBindJSON(&req); err != nil { | ||
| println("JSON bind error: %v (type: %T)", err, err) |
There was a problem hiding this comment.
Remove debug println statement.
The println call with format string syntax appears to be debug code. Remove it or replace with structured logging (e.g., using a logger instance) for production observability.
🧹 Proposed fix
var req ShowModelRequest
if err := c.ShouldBindJSON(&req); err != nil {
- println("JSON bind error: %v (type: %T)", err, err)
c.JSON(http.StatusOK, gin.H{📝 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.
| println("JSON bind error: %v (type: %T)", err, err) | |
| var req ShowModelRequest | |
| if err := c.ShouldBindJSON(&req); err != nil { | |
| c.JSON(http.StatusOK, gin.H{ |
🤖 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/handler/models.go` at line 49, Remove the debug println call that
uses printf-style formatting (println("JSON bind error: %v (type: %T)", err,
err)) and replace it with a structured log call using your project's logger
(e.g., processLogger, logger, or standard log) so the error and its type are
recorded properly; reference the existing error variable err and ensure the
message is descriptive (e.g., "JSON bind error") while passing err as structured
context instead of using println.
| c.JSON(http.StatusOK, gin.H{ | ||
| "code": common.CodeBadRequest, | ||
| "message": err.Error(), | ||
| }) | ||
| return |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Description: Check HTTP status code usage pattern in other handlers
# Search for c.JSON calls in handler files to see status code patterns
rg -n -A3 -B1 'c\.JSON\(' --type=go -g 'internal/handler/*.go' | head -100Repository: infiniflow/ragflow
Length of output: 5329
🏁 Script executed:
#!/bin/bash
# Inspect the exact status-code usage in internal/handler/models.go around the reported lines
sed -n '1,140p' internal/handler/models.go | nl -ba | sed -n '35,110p'
# Show all c.JSON(http.Status*...) occurrences in internal/handler/models.go
rg -n 'c\.JSON\((http\.Status[A-Za-z0-9_]+)' internal/handler/models.goRepository: infiniflow/ragflow
Length of output: 293
Align HTTP status codes with the handlers’ established error contract.
internal/handler/models.go returns http.StatusOK for both success and error paths (reported at lines 50-54, 65-69, 82-86, 90-94) while signaling failures via the JSON code/message fields. This matches internal/handler/llm.go, but internal/handler/connector.go uses http.StatusBadRequest and http.StatusInternalServerError in some error cases, so the convention is inconsistent across handlers. Pick one approach (either “always 200 + JSON code” and document it, or use proper 4xx/5xx status codes) and apply it consistently.
🤖 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/handler/models.go` around lines 50 - 54, Handlers in
internal/handler/models.go currently always return http.StatusOK for errors
(using c.JSON(http.StatusOK,...)) which is inconsistent with connector.go; pick
a single convention—prefer using proper HTTP status codes—and update the error
responses in models.go to return the matching 4xx/5xx status (e.g.,
http.StatusBadRequest or http.StatusInternalServerError) when sending JSON with
common.CodeBadRequest/common.CodeInternalError, update the c.JSON(...) calls
(the ones that currently pass http.StatusOK) to the appropriate http status, and
ensure the same convention is applied across internal/handler/llm.go and
internal/handler/connector.go for consistency.
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (1)
internal/service/model_service.go (1)
2420-2421:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winIncomplete bounds check allows out-of-range panic.
Line 2420 validates the start index but not the end. When
(pageIndex+1)*pageSizeexceedslen(models), line 2421 panics. For example, withlen(models)=10,pageIndex=0,pageSize=20: the condition0*20 < 10passes, butmodels[0:20]panics.🛡️ Proposed fix
- if pageSize > 0 && pageIndex >= 0 && pageIndex*pageSize < len(models) { - return models[pageIndex*pageSize : (pageIndex+1)*pageSize], nil + if pageSize > 0 && pageIndex >= 0 { + start := pageIndex * pageSize + if start >= len(models) { + return []map[string]interface{}{}, nil + } + end := start + pageSize + if end > len(models) { + end = len(models) + } + return models[start:end], 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/service/model_service.go` around lines 2420 - 2421, The current bounds check only ensures the start index but not the end, causing a panic when (pageIndex+1)*pageSize > len(models); update the logic that slices the models slice (using pageSize, pageIndex, models) to compute a safe end index (e.g. end := min((pageIndex+1)*pageSize, len(models))) and return models[pageIndex*pageSize:end], or change the condition to require (pageIndex+1)*pageSize <= len(models) before slicing so the end index never exceeds len(models).
🤖 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 @.github/workflows/tests.yml:
- Around line 144-161: Uncomment and restore the CI steps that prepare test
resources and run Go tests: re-enable the "Prepare test resources" block that
clones the resource repo, checks out the pinned ref, creates
/usr/share/infinity/resource and symlinks resource/wordnet, and re-enable the
"Test Go packages" step that computes packages via packages=$(go list
./internal/... | grep -vE '/storage(/|$)') and runs CGO_ENABLED=1 with GOPROXY
to execute go test -count=1 ${packages}; ensure both blocks (names "Prepare test
resources" and "Test Go packages") are present and use the original env and
commands so CLI/model-catalog regressions and tokenizer/resource-dependent flows
are validated.
In `@internal/service/model_service.go`:
- Around line 2426-2428: The ShowModel method currently returns (nil, nil) when
dao.GetModelProviderManager().GetModelByNameOrAlias(modelName) yields nil;
update ShowModel to check the returned model and return a non-nil error when
it's not found (e.g., return nil and fmt.Errorf("model %s not found", modelName)
or a package-level sentinel error) so callers can distinguish "not found" from
success; keep the signature of ShowModel unchanged and reference
dao.GetModelProviderManager().GetModelByNameOrAlias and ShowModel in your
change.
---
Duplicate comments:
In `@internal/service/model_service.go`:
- Around line 2420-2421: The current bounds check only ensures the start index
but not the end, causing a panic when (pageIndex+1)*pageSize > len(models);
update the logic that slices the models slice (using pageSize, pageIndex,
models) to compute a safe end index (e.g. end := min((pageIndex+1)*pageSize,
len(models))) and return models[pageIndex*pageSize:end], or change the condition
to require (pageIndex+1)*pageSize <= len(models) before slicing so the end index
never exceeds len(models).
🪄 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: e74af033-eadf-465f-a1f1-6acc7b55832b
📒 Files selected for processing (3)
.github/workflows/tests.ymlinternal/entity/model.gointernal/service/model_service.go
🚧 Files skipped from review as they are similar to previous changes (1)
- internal/entity/model.go
| # - name: Prepare test resources | ||
| # run: | | ||
| # RESOURCE_REPO=https://github.com/infiniflow/resource.git | ||
| # RESOURCE_REF=549feaaf998954d65b668667f009125bc84a9c5e | ||
| # rm -rf /tmp/resource | ||
| # git clone "${RESOURCE_REPO}" /tmp/resource | ||
| # git -C /tmp/resource checkout "${RESOURCE_REF}" | ||
| # sudo mkdir -p /usr/share/infinity | ||
| # sudo ln -sf /tmp/resource /usr/share/infinity/resource | ||
| # mkdir -p resource | ||
| # ln -sf /tmp/resource/wordnet resource/wordnet | ||
| # | ||
| # - name: Test Go packages | ||
| # run: | | ||
| # set -euo pipefail | ||
| # packages=$(go list ./internal/... | grep -vE '/storage(/|$)') | ||
| # CGO_ENABLED=1 GOPROXY=${GOPROXY:-https://goproxy.cn,https://proxy.golang.org,direct} \ | ||
| # go test -count=1 ${packages} |
There was a problem hiding this comment.
Re-enable Go test execution; current workflow now skips Go regression coverage.
At Line 156 onward, commenting out Test Go packages removes CI validation for ./internal/... while this PR series introduces Go CLI/model-catalog changes. Also, the commented resource setup at Line 144 previously prepared /usr/share/infinity/resource, which is a known runtime default path for tokenizer/resource-dependent flows. This combination materially increases regression risk.
Suggested fix
-# - name: Prepare test resources
-# run: |
-# RESOURCE_REPO=https://github.com/infiniflow/resource.git
-# RESOURCE_REF=549feaaf998954d65b668667f009125bc84a9c5e
-# rm -rf /tmp/resource
-# git clone "${RESOURCE_REPO}" /tmp/resource
-# git -C /tmp/resource checkout "${RESOURCE_REF}"
-# sudo mkdir -p /usr/share/infinity
-# sudo ln -sf /tmp/resource /usr/share/infinity/resource
-# mkdir -p resource
-# ln -sf /tmp/resource/wordnet resource/wordnet
-#
-# - name: Test Go packages
-# run: |
-# set -euo pipefail
-# packages=$(go list ./internal/... | grep -vE '/storage(/|$)')
-# CGO_ENABLED=1 GOPROXY=${GOPROXY:-https://goproxy.cn,https://proxy.golang.org,direct} \
-# go test -count=1 ${packages}
+ - name: Prepare test resources
+ run: |
+ RESOURCE_REPO=https://github.com/infiniflow/resource.git
+ RESOURCE_REF=549feaaf998954d65b668667f009125bc84a9c5e
+ rm -rf /tmp/resource
+ git clone "${RESOURCE_REPO}" /tmp/resource
+ git -C /tmp/resource checkout "${RESOURCE_REF}"
+ sudo mkdir -p /usr/share/infinity
+ sudo ln -sf /tmp/resource /usr/share/infinity/resource
+ mkdir -p resource
+ ln -sf /tmp/resource/wordnet resource/wordnet
+
+ - name: Test Go packages
+ run: |
+ set -euo pipefail
+ packages=$(go list ./internal/... | grep -vE '/storage(/|$)')
+ CGO_ENABLED=1 GOPROXY=${GOPROXY:-https://goproxy.cn,https://proxy.golang.org,direct} \
+ go test -count=1 ${packages}📝 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.
| # - name: Prepare test resources | |
| # run: | | |
| # RESOURCE_REPO=https://github.com/infiniflow/resource.git | |
| # RESOURCE_REF=549feaaf998954d65b668667f009125bc84a9c5e | |
| # rm -rf /tmp/resource | |
| # git clone "${RESOURCE_REPO}" /tmp/resource | |
| # git -C /tmp/resource checkout "${RESOURCE_REF}" | |
| # sudo mkdir -p /usr/share/infinity | |
| # sudo ln -sf /tmp/resource /usr/share/infinity/resource | |
| # mkdir -p resource | |
| # ln -sf /tmp/resource/wordnet resource/wordnet | |
| # | |
| # - name: Test Go packages | |
| # run: | | |
| # set -euo pipefail | |
| # packages=$(go list ./internal/... | grep -vE '/storage(/|$)') | |
| # CGO_ENABLED=1 GOPROXY=${GOPROXY:-https://goproxy.cn,https://proxy.golang.org,direct} \ | |
| # go test -count=1 ${packages} | |
| - name: Prepare test resources | |
| run: | | |
| RESOURCE_REPO=https://github.com/infiniflow/resource.git | |
| RESOURCE_REF=549feaaf998954d65b668667f009125bc84a9c5e | |
| rm -rf /tmp/resource | |
| git clone "${RESOURCE_REPO}" /tmp/resource | |
| git -C /tmp/resource checkout "${RESOURCE_REF}" | |
| sudo mkdir -p /usr/share/infinity | |
| sudo ln -sf /tmp/resource /usr/share/infinity/resource | |
| mkdir -p resource | |
| ln -sf /tmp/resource/wordnet resource/wordnet | |
| - name: Test Go packages | |
| run: | | |
| set -euo pipefail | |
| packages=$(go list ./internal/... | grep -vE '/storage(/|$)') | |
| CGO_ENABLED=1 GOPROXY=${GOPROXY:-https://goproxy.cn,https://proxy.golang.org,direct} \ | |
| go test -count=1 ${packages} |
🤖 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 @.github/workflows/tests.yml around lines 144 - 161, Uncomment and restore
the CI steps that prepare test resources and run Go tests: re-enable the
"Prepare test resources" block that clones the resource repo, checks out the
pinned ref, creates /usr/share/infinity/resource and symlinks resource/wordnet,
and re-enable the "Test Go packages" step that computes packages via
packages=$(go list ./internal/... | grep -vE '/storage(/|$)') and runs
CGO_ENABLED=1 with GOPROXY to execute go test -count=1 ${packages}; ensure both
blocks (names "Prepare test resources" and "Test Go packages") are present and
use the original env and commands so CLI/model-catalog regressions and
tokenizer/resource-dependent flows are validated.
| func (m *ModelProviderService) ShowModel(modelName string) (*entity.Model, error) { | ||
| return dao.GetModelProviderManager().GetModelByNameOrAlias(modelName), nil | ||
| } |
There was a problem hiding this comment.
Return an error when model is not found.
GetModelByNameOrAlias likely returns nil when the model doesn't exist, but this method always returns error = nil. Callers receive (nil, nil) and cannot distinguish "not found" from success, risking nil-pointer dereferences downstream.
🐛 Proposed fix
func (m *ModelProviderService) ShowModel(modelName string) (*entity.Model, error) {
- return dao.GetModelProviderManager().GetModelByNameOrAlias(modelName), nil
+ model := dao.GetModelProviderManager().GetModelByNameOrAlias(modelName)
+ if model == nil {
+ return nil, fmt.Errorf("model %q not found", modelName)
+ }
+ return model, 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/service/model_service.go` around lines 2426 - 2428, The ShowModel
method currently returns (nil, nil) when
dao.GetModelProviderManager().GetModelByNameOrAlias(modelName) yields nil;
update ShowModel to check the returned model and return a non-nil error when
it's not found (e.g., return nil and fmt.Errorf("model %s not found", modelName)
or a package-level sentinel error) so callers can distinguish "not found" from
success; keep the signature of ShowModel unchanged and reference
dao.GetModelProviderManager().GetModelByNameOrAlias and ShowModel in your
change.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15786 +/- ##
=======================================
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. 🚀 New features to boost your workflow:
|
The Go test steps were commented out by infiniflow#15786 (due to resource clone failures). Re-enable with run-scoped resource path to prevent cross-run deletion races on self-hosted runners.
What problem does this PR solve?