Repository navigation
Go CLI: update list supported models - #15845
Conversation
Signed-off-by: Jin Hai <[email protected]>
📝 WalkthroughWalkthroughThis PR refactors the model discovery API across 60+ model provider drivers, changing ListModels from returning raw model ID strings to returning structured ListModelResponse objects with metadata. Provider manager initialization is moved to a global singleton pattern. Optional MaxTokens and Dimension fields are added to the Model type, with nil-safe dereferencing throughout the service layer. ChangesModel Listing API & Provider Manager Refactor
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested labels
Suggested reviewers
🚥 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 |
There was a problem hiding this comment.
Actionable comments posted: 14
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/entity/models/model.go (1)
516-524:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winNil-pointer dereference when
MaxTokensis nil.
model.MaxTokensis now a pointer and may be nil. Dereferencing it at line 518 without a nil check will cause a panic.🐛 Proposed fix: add nil guard
case "max_tokens": if maxVal, ok := filterValue.(int); ok { - if *model.MaxTokens < maxVal { + if model.MaxTokens == nil || *model.MaxTokens < maxVal { matchFilter = false resp.Code = 400 - resp.Message = fmt.Sprintf("Model does not meet filter criteria: max_tokens (%d) < %d", - model.MaxTokens, maxVal) + if model.MaxTokens == nil { + resp.Message = fmt.Sprintf("Model does not meet filter criteria: max_tokens is not set") + } else { + resp.Message = fmt.Sprintf("Model does not meet filter criteria: max_tokens (%d) < %d", + *model.MaxTokens, maxVal) + } } }🤖 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/model.go` around lines 516 - 524, The "max_tokens" filter case dereferences model.MaxTokens without a nil check causing a panic; update the case in the filtering function to first check if model.MaxTokens == nil and, if so, set matchFilter = false and populate resp.Code and resp.Message (e.g., explain max_tokens is missing), otherwise safely compare *model.MaxTokens to maxVal and keep the existing logic that sets matchFilter = false and resp fields when the value is too small; ensure you reference model.MaxTokens, matchFilter, resp.Code and resp.Message when making the changes.
🧹 Nitpick comments (3)
internal/entity/models/model.go (2)
428-436: ⚡ Quick winInconsistent
MaxTokenshandling compared toListAllModels.
ListAllModels(lines 381-383) conditionally includesmax_tokensonly when non-nil and dereferences it. Here,max_tokensis always included and may be nil. Consider aligning the behavior for consistent API responses.♻️ Proposed fix: align with ListAllModels pattern
modelList := []map[string]interface{}{} for _, model := range provider.Models { modelData := map[string]interface{}{ "name": model.Name, - "max_tokens": model.MaxTokens, "model_types": model.ModelTypes, } + if model.MaxTokens != nil { + modelData["max_tokens"] = *model.MaxTokens + } modelList = append(modelList, modelData) }🤖 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/model.go` around lines 428 - 436, The model serialization here always includes "max_tokens" even if nil; update the loop in the function that builds modelList to match ListAllModels' pattern by only adding "max_tokens" when model.MaxTokens != nil and storing *model.MaxTokens (dereferenced) instead of the pointer. Locate the loop over provider.Models (where modelData is created) and change the map construction so "max_tokens" is conditionally added when non-nil, keeping "name" and "model_types" unchanged.
296-300: 💤 Low valueHardcoded path may reduce flexibility.
The path
conf/all_models.jsonis hardcoded while provider configs use thedirPathparameter. Consider making this path configurable or deriving it relative todirPathfor consistency.🤖 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/model.go` around lines 296 - 300, The code reads a hardcoded "conf/all_models.json" via os.ReadFile which ignores the function's dirPath parameter; change the file resolution to derive the config path from dirPath (or accept a configurable path) before calling os.ReadFile so the function uses filepath.Join(dirPath, "conf", "all_models.json") or a passed-in filename; update the read call that assigns to data and err (the os.ReadFile usage) to use the derived/configurable path and adjust any callers if you add a parameter.internal/entity/models/stepfun.go (1)
371-371: 💤 Low valueConsider pre-allocating slice capacity.
Since
len(data)is known at this point, pre-allocating the slice capacity can avoid reallocation during append operations. Other drivers (tokenhub, tokenpony) follow this pattern.♻️ Suggested optimization
- models := make([]ListModelResponse, 0) + models := make([]ListModelResponse, 0, len(data))🤖 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/stepfun.go` at line 371, Pre-allocate the slice capacity for models since len(data) is known: change the allocation of models (type ListModelResponse) to reserve capacity using make with a third argument (e.g., make([]ListModelResponse, 0, len(data))) or allocate directly with length and fill by index; update places that append to models accordingly to avoid repeated reallocations when iterating over data.
🤖 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/baidu.go`:
- Around line 798-805: The loop over result["data"] uses unchecked type
assertions and can panic; update the code that builds the models slice (the
block creating models := make([]ListModelResponse, 0) and iterating over
result["data"]) to safely assert types: first check that result["data"] exists
and is a []interface{} (with an ok check), then for each entry assert it is a
map[string]interface{} and safely extract "id" as a string (with ok checks)
before appending a ListModelResponse{Name: modelName}; if any check fails, skip
that entry (or handle gracefully) so the function (in baidu.go) never panics on
malformed API responses.
In `@internal/entity/models/gitee.go`:
- Around line 903-920: The lookup uses model.ID when calling
GetProviderManager().GetModelByNameOrAlias but the canonical name used later
includes the OwnedBy suffix; update the code to build the fully-qualified
modelName (using model.ID and model.OwnedBy) before calling
GetModelByNameOrAlias so the provider manager can find metadata for names like
"ModelID@OwnedBy"; then populate modelResponse from modelEntity as before
(fields: Dimension, MaxTokens, ModelTypes, Thinking) and append to models.
Ensure you still set modelResponse.Name to the final qualified name (model.ID +
"@" + model.OwnedBy when OwnedBy != "").
In `@internal/entity/models/huggingface.go`:
- Around line 514-519: The loop that builds []ListModelResponse uses unchecked
type assertions on result["data"], each element, and the "id" field which can
panic; update the code that iterates over result (used when building models) to
first check that result["data"] is a []interface{} (use a type assertion with
ok), then for each element assert it's a map[string]interface{} with ok, and
that modelMap["id"] is a string before appending to models (skip or continue on
invalid entries and optionally log the unexpected shapes); modify the block that
creates models and references modelMap/modelName/ListModelResponse accordingly
to use these guarded checks.
In `@internal/entity/models/jina.go`:
- Around line 358-363: The loop over result["data"] uses unchecked type
assertions and can panic; update the code that builds models (the slice of
ListModelResponse) to safely type-assert result["data"] to []interface{} (check
the ok boolean), iterate only if successful, for each element assert it is
map[string]interface{} (with an ok check), then extract "name" as a string with
an ok check before creating a ListModelResponse; on any failed assertion skip
the item and optionally log a warning (do not panic) so the driver remains
resilient.
In `@internal/entity/models/lmstudio.go`:
- Around line 564-569: The loop building models from result uses unchecked type
assertions and can panic; update the code that constructs the
[]ListModelResponse from result to first verify result["data"] is a
[]interface{} (using the comma-ok/type switch), then for each element assert it
is a map[string]interface{} and that map["id"] is a string (using comma-ok),
skipping or logging entries that fail validation instead of panicking; keep the
output type as []ListModelResponse and only append valid Name values to models
to preserve existing behavior.
In `@internal/entity/models/model_test.go`:
- Around line 138-143: After calling InitProviderManager(dir) you must obtain
the manager instance before using it; add a call to GetProviderManager() and
assign it to pm (e.g., pm := GetProviderManager()) immediately after
InitProviderManager returns, then use pm.FindProvider("CoHere") as intended so
pm is defined and the test compiles.
- Around line 288-293: After calling InitProviderManager(dir) you never obtain
the manager instance, causing pm to be undefined; add a call to
GetProviderManager() and assign it to pm (e.g., pm := GetProviderManager())
immediately after InitProviderManager(dir) so subsequent uses of pm
(FindProvider, etc.) compile; ensure the declaration is in the same scope as the
test assertions that reference pm.
- Around line 201-206: The test calls InitProviderManager(dir) but never assigns
pm; add pm := GetProviderManager() immediately after InitProviderManager(dir)
returns and before any use of pm so the subsequent calls to pm.FindProvider(...)
and other pm.* references (used in this file) compile; ensure you use the
package-level GetProviderManager function to obtain the manager instance and
then proceed with existing assertions.
In `@internal/entity/models/model.go`:
- Around line 394-402: GetModelByNameOrAlias lowercases the input but
Alias2ModelIndex is populated with original-case keys, causing lookups to fail
for mixed-case aliases; fix by normalizing keys when building Alias2ModelIndex
(ensure every alias inserted into ProviderManager.Alias2ModelIndex is
strings.ToLower(alias)) so GetModelByNameOrAlias can reliably lowercase the
input and find the index, or alternatively remove the lowercase call in
GetModelByNameOrAlias and perform lookup using the original alias case—update
the map construction code paths that populate Alias2ModelIndex (where aliases
are added) to use the normalized form, and keep GetModelByNameOrAlias using
strings.ToLower(modelName) as currently implemented.
In `@internal/entity/models/ollama.go`:
- Around line 519-523: The loop over result["models"] in ollama.go uses unsafe
type assertions and can panic; update the code that iterates over
result["models"] to use safe type assertions (check ok when casting
result["models"] to []interface{} and when casting each model to
map[string]interface{} and the "name" field to string), skip entries that fail
casts instead of panicking, and append valid names to ListModelResponse{Name:
...}; ensure you reference the existing variables/result map and the
ListModelResponse type so behavior stays consistent with other drivers (novita,
nvidia, openai).
In `@internal/entity/models/openrouter.go`:
- Around line 795-800: The loop building models from result["data"] uses
unchecked type assertions and can panic; update the code that iterates over
result["data"] to safely assert types (check ok values) for the top-level slice,
each element being a map[string]interface{}, and the "id" field being a string
before using them (symbols: result, models, ListModelResponse, modelMap,
modelName); skip or log invalid entries instead of asserting, and only append
ListModelResponse{Name: modelName} when all assertions succeed.
In `@internal/entity/models/orcarouter.go`:
- Around line 467-472: The loop blindly type-asserts result["data"] and each
model to concrete types which can panic; change the parsing in the
ListModelResponse construction to perform safe type checks (use a type assertion
with the "ok" idiom or a type switch) for result["data"] to ensure it's a
[]interface{}, for each model to ensure it's a map[string]interface{}, and for
the "id" field to ensure it's a string, skip or log entries that fail validation
instead of asserting; update the block that builds models (references: result,
models, modelMap, modelName, ListModelResponse) to only append when all checks
succeed.
In `@internal/entity/models/xunfei.go`:
- Around line 439-443: In ListModels, avoid unchecked type assertions on
result["data"] and its elements (currently producing modelMap :=
model.(map[string]interface{}) and modelMap["id"].(string)); instead validate
types with comma-ok checks and return a descriptive error if the payload shape
is unexpected (e.g., ensure result["data"] exists and is []interface{}, each
item is map[string]interface{}, and "id" is a string) before appending to the
models slice (ListModelResponse); update error handling to propagate a clear
error rather than allowing a panic.
In `@internal/service/model_service.go`:
- Around line 247-257: The slice result is left nil when modelList is empty,
causing JSON serialization to emit null; initialize result as an empty slice
(e.g. result := make([]map[string]interface{}, 0)) before the loop that iterates
modelList so you always return an empty array instead of nil from the function
that builds maps from model.Name, model.Dimension, model.MaxTokens,
model.ModelTypes, model.Thinking.
---
Outside diff comments:
In `@internal/entity/models/model.go`:
- Around line 516-524: The "max_tokens" filter case dereferences model.MaxTokens
without a nil check causing a panic; update the case in the filtering function
to first check if model.MaxTokens == nil and, if so, set matchFilter = false and
populate resp.Code and resp.Message (e.g., explain max_tokens is missing),
otherwise safely compare *model.MaxTokens to maxVal and keep the existing logic
that sets matchFilter = false and resp fields when the value is too small;
ensure you reference model.MaxTokens, matchFilter, resp.Code and resp.Message
when making the changes.
---
Nitpick comments:
In `@internal/entity/models/model.go`:
- Around line 428-436: The model serialization here always includes "max_tokens"
even if nil; update the loop in the function that builds modelList to match
ListAllModels' pattern by only adding "max_tokens" when model.MaxTokens != nil
and storing *model.MaxTokens (dereferenced) instead of the pointer. Locate the
loop over provider.Models (where modelData is created) and change the map
construction so "max_tokens" is conditionally added when non-nil, keeping "name"
and "model_types" unchanged.
- Around line 296-300: The code reads a hardcoded "conf/all_models.json" via
os.ReadFile which ignores the function's dirPath parameter; change the file
resolution to derive the config path from dirPath (or accept a configurable
path) before calling os.ReadFile so the function uses filepath.Join(dirPath,
"conf", "all_models.json") or a passed-in filename; update the read call that
assigns to data and err (the os.ReadFile usage) to use the derived/configurable
path and adjust any callers if you add a parameter.
In `@internal/entity/models/stepfun.go`:
- Line 371: Pre-allocate the slice capacity for models since len(data) is known:
change the allocation of models (type ListModelResponse) to reserve capacity
using make with a third argument (e.g., make([]ListModelResponse, 0, len(data)))
or allocate directly with length and fill by index; update places that append to
models accordingly to avoid repeated reallocations when iterating over data.
🪄 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: 17a9b849-cb1b-4387-bfbf-0aa9cfc34e0d
📒 Files selected for processing (68)
internal/dao/database.gointernal/entity/models/302ai.gointernal/entity/models/aliyun.gointernal/entity/models/anthropic.gointernal/entity/models/astraflow.gointernal/entity/models/avian.gointernal/entity/models/azure_openai.gointernal/entity/models/baichuan.gointernal/entity/models/baidu.gointernal/entity/models/bedrock.gointernal/entity/models/builtin.gointernal/entity/models/cohere.gointernal/entity/models/cometapi.gointernal/entity/models/deepinfra.gointernal/entity/models/deepseek.gointernal/entity/models/dummy.gointernal/entity/models/fishaudio.gointernal/entity/models/futurmix.gointernal/entity/models/gitee.gointernal/entity/models/google.gointernal/entity/models/gpustack.gointernal/entity/models/groq.gointernal/entity/models/huaweicloud.gointernal/entity/models/huggingface.gointernal/entity/models/hunyuan.gointernal/entity/models/jiekouai.gointernal/entity/models/jina.gointernal/entity/models/lmstudio.gointernal/entity/models/localai.gointernal/entity/models/longcat.gointernal/entity/models/mineru.gointernal/entity/models/mineru_local.gointernal/entity/models/minimax.gointernal/entity/models/mistral.gointernal/entity/models/model.gointernal/entity/models/model_test.gointernal/entity/models/modelscope.gointernal/entity/models/moonshot.gointernal/entity/models/n1n.gointernal/entity/models/novita.gointernal/entity/models/nvidia.gointernal/entity/models/ollama.gointernal/entity/models/openai.gointernal/entity/models/openrouter.gointernal/entity/models/orcarouter.gointernal/entity/models/paddleocr.gointernal/entity/models/paddleocr_local.gointernal/entity/models/perplexity.gointernal/entity/models/ppio.gointernal/entity/models/qiniu.gointernal/entity/models/replicate.gointernal/entity/models/siliconflow.gointernal/entity/models/stepfun.gointernal/entity/models/togetherai.gointernal/entity/models/tokenhub.gointernal/entity/models/tokenpony.gointernal/entity/models/types.gointernal/entity/models/upstage.gointernal/entity/models/vllm.gointernal/entity/models/volcengine.gointernal/entity/models/voyage.gointernal/entity/models/xai.gointernal/entity/models/xiaomi.gointernal/entity/models/xinference.gointernal/entity/models/xunfei.gointernal/entity/models/zhipu-ai.gointernal/handler/providers.gointernal/service/model_service.go
| models := make([]ListModelResponse, 0) | ||
| for _, model := range result["data"].([]interface{}) { | ||
| modelMap := model.(map[string]interface{}) | ||
| modelName := modelMap["id"].(string) | ||
| models = append(models, modelName) | ||
| models = append(models, ListModelResponse{ | ||
| Name: modelName, | ||
| }) | ||
| } |
There was a problem hiding this comment.
Unchecked type assertions can cause runtime panics.
Lines 799-801 contain unchecked type assertions that will panic if the API response structure differs from expectations (e.g., missing data field, non-object entries, or missing/non-string id). Other drivers in this PR (astraflow, azure_openai) handle this safely with ok checks.
🐛 Proposed fix to add safe type assertions
// convert result["data"] to []map[string]interface{}
models := make([]ListModelResponse, 0)
- for _, model := range result["data"].([]interface{}) {
- modelMap := model.(map[string]interface{})
- modelName := modelMap["id"].(string)
+ data, ok := result["data"].([]interface{})
+ if !ok {
+ return nil, fmt.Errorf("invalid models list format")
+ }
+ for _, model := range data {
+ modelMap, ok := model.(map[string]interface{})
+ if !ok {
+ continue
+ }
+ modelName, ok := modelMap["id"].(string)
+ if !ok || modelName == "" {
+ continue
+ }
models = append(models, ListModelResponse{
Name: 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` around lines 798 - 805, The loop over
result["data"] uses unchecked type assertions and can panic; update the code
that builds the models slice (the block creating models :=
make([]ListModelResponse, 0) and iterating over result["data"]) to safely assert
types: first check that result["data"] exists and is a []interface{} (with an ok
check), then for each entry assert it is a map[string]interface{} and safely
extract "id" as a string (with ok checks) before appending a
ListModelResponse{Name: modelName}; if any check fails, skip that entry (or
handle gracefully) so the function (in baidu.go) never panics on malformed API
responses.
| 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 | ||
| } | ||
| models = append(models, modelName) | ||
| 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) | ||
| } |
There was a problem hiding this comment.
Fix metadata lookup timing: qualify model name before lookup.
The provider lookup at line 907 uses the base model.ID, but the final modelResponse.Name includes the @OwnedBy suffix (lines 908-910). If the provider manager indexes models by their fully-qualified names (e.g., "DeepSeek-V4-Flash@deepseek-ai"), this lookup will fail to retrieve metadata for models that have an OwnedBy field set.
As a result, Dimension, MaxTokens, ModelTypes, and Thinking will remain nil for qualified model names, even when metadata exists in the provider manager under the qualified key.
🔧 Proposed fix
for _, model := range modelList.Models {
modelName := model.ID
+ if model.OwnedBy != "" {
+ modelName = model.ID + "@" + model.OwnedBy
+ }
var modelResponse ListModelResponse
pm := GetProviderManager()
modelEntity := pm.GetModelByNameOrAlias(modelName)
- if model.OwnedBy != "" {
- modelName = model.ID + "@" + model.OwnedBy
- }
modelResponse.Name = 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/gitee.go` around lines 903 - 920, The lookup uses
model.ID when calling GetProviderManager().GetModelByNameOrAlias but the
canonical name used later includes the OwnedBy suffix; update the code to build
the fully-qualified modelName (using model.ID and model.OwnedBy) before calling
GetModelByNameOrAlias so the provider manager can find metadata for names like
"ModelID@OwnedBy"; then populate modelResponse from modelEntity as before
(fields: Dimension, MaxTokens, ModelTypes, Thinking) and append to models.
Ensure you still set modelResponse.Name to the final qualified name (model.ID +
"@" + model.OwnedBy when OwnedBy != "").
| models := make([]ListModelResponse, 0) | ||
| for _, model := range result["data"].([]interface{}) { | ||
| modelMap := model.(map[string]interface{}) | ||
| modelName := modelMap["id"].(string) | ||
| models = append(models, modelName) | ||
| models = append(models, ListModelResponse{Name: modelName}) | ||
| } |
There was a problem hiding this comment.
Guard type assertions to prevent panics.
Lines 515-517 use unchecked type assertions that will panic if the API response shape is unexpected. If result["data"] is not []interface{}, or if an element is not map[string]interface{}, or if "id" is not a string, the driver will crash.
🛡️ Proposed fix
models := make([]ListModelResponse, 0)
- for _, model := range result["data"].([]interface{}) {
- modelMap := model.(map[string]interface{})
- modelName := modelMap["id"].(string)
+ data, ok := result["data"].([]interface{})
+ if !ok {
+ return nil, fmt.Errorf("invalid data format in models list response")
+ }
+ for _, model := range data {
+ modelMap, ok := model.(map[string]interface{})
+ if !ok {
+ continue
+ }
+ modelName, ok := modelMap["id"].(string)
+ if !ok || modelName == "" {
+ continue
+ }
models = append(models, ListModelResponse{Name: 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.
| models := make([]ListModelResponse, 0) | |
| for _, model := range result["data"].([]interface{}) { | |
| modelMap := model.(map[string]interface{}) | |
| modelName := modelMap["id"].(string) | |
| models = append(models, modelName) | |
| models = append(models, ListModelResponse{Name: modelName}) | |
| } | |
| models := make([]ListModelResponse, 0) | |
| data, ok := result["data"].([]interface{}) | |
| if !ok { | |
| return nil, fmt.Errorf("invalid data format in models list response") | |
| } | |
| for _, model := range data { | |
| modelMap, ok := model.(map[string]interface{}) | |
| if !ok { | |
| continue | |
| } | |
| modelName, ok := modelMap["id"].(string) | |
| if !ok || modelName == "" { | |
| continue | |
| } | |
| models = append(models, ListModelResponse{Name: 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/huggingface.go` around lines 514 - 519, The loop that
builds []ListModelResponse uses unchecked type assertions on result["data"],
each element, and the "id" field which can panic; update the code that iterates
over result (used when building models) to first check that result["data"] is a
[]interface{} (use a type assertion with ok), then for each element assert it's
a map[string]interface{} with ok, and that modelMap["id"] is a string before
appending to models (skip or continue on invalid entries and optionally log the
unexpected shapes); modify the block that creates models and references
modelMap/modelName/ListModelResponse accordingly to use these guarded checks.
| models := make([]ListModelResponse, 0) | ||
| for _, model := range result["data"].([]interface{}) { | ||
| modelMap := model.(map[string]interface{}) | ||
| modelName := modelMap["name"].(string) | ||
| models = append(models, modelName) | ||
| models = append(models, ListModelResponse{Name: modelName}) | ||
| } |
There was a problem hiding this comment.
Guard type assertions to prevent panics.
Lines 359-361 use unchecked type assertions that will panic if the API response shape is unexpected. If result["data"] is not []interface{}, or if an element is not map[string]interface{}, or if "name" is not a string, the driver will crash.
🛡️ Proposed fix
models := make([]ListModelResponse, 0)
- for _, model := range result["data"].([]interface{}) {
- modelMap := model.(map[string]interface{})
- modelName := modelMap["name"].(string)
+ data, ok := result["data"].([]interface{})
+ if !ok {
+ return nil, fmt.Errorf("invalid data format in models list response")
+ }
+ for _, model := range data {
+ modelMap, ok := model.(map[string]interface{})
+ if !ok {
+ continue
+ }
+ modelName, ok := modelMap["name"].(string)
+ if !ok || modelName == "" {
+ continue
+ }
models = append(models, ListModelResponse{Name: 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.
| models := make([]ListModelResponse, 0) | |
| for _, model := range result["data"].([]interface{}) { | |
| modelMap := model.(map[string]interface{}) | |
| modelName := modelMap["name"].(string) | |
| models = append(models, modelName) | |
| models = append(models, ListModelResponse{Name: modelName}) | |
| } | |
| models := make([]ListModelResponse, 0) | |
| data, ok := result["data"].([]interface{}) | |
| if !ok { | |
| return nil, fmt.Errorf("invalid data format in models list response") | |
| } | |
| for _, model := range data { | |
| modelMap, ok := model.(map[string]interface{}) | |
| if !ok { | |
| continue | |
| } | |
| modelName, ok := modelMap["name"].(string) | |
| if !ok || modelName == "" { | |
| continue | |
| } | |
| models = append(models, ListModelResponse{Name: 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/jina.go` around lines 358 - 363, The loop over
result["data"] uses unchecked type assertions and can panic; update the code
that builds models (the slice of ListModelResponse) to safely type-assert
result["data"] to []interface{} (check the ok boolean), iterate only if
successful, for each element assert it is map[string]interface{} (with an ok
check), then extract "name" as a string with an ok check before creating a
ListModelResponse; on any failed assertion skip the item and optionally log a
warning (do not panic) so the driver remains resilient.
| models := make([]ListModelResponse, 0) | ||
| for _, model := range result["data"].([]interface{}) { | ||
| modelMap := model.(map[string]interface{}) | ||
| modelName := modelMap["id"].(string) | ||
| models = append(models, modelName) | ||
| models = append(models, ListModelResponse{Name: modelName}) | ||
| } |
There was a problem hiding this comment.
Guard type assertions to prevent panics.
Lines 565-567 use unchecked type assertions that will panic if the API response shape is unexpected. If result["data"] is not []interface{}, or if an element is not map[string]interface{}, or if "id" is not a string, the driver will crash.
🛡️ Proposed fix
models := make([]ListModelResponse, 0)
- for _, model := range result["data"].([]interface{}) {
- modelMap := model.(map[string]interface{})
- modelName := modelMap["id"].(string)
+ data, ok := result["data"].([]interface{})
+ if !ok {
+ return nil, fmt.Errorf("invalid data format in models list response")
+ }
+ for _, model := range data {
+ modelMap, ok := model.(map[string]interface{})
+ if !ok {
+ continue
+ }
+ modelName, ok := modelMap["id"].(string)
+ if !ok || modelName == "" {
+ continue
+ }
models = append(models, ListModelResponse{Name: 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.
| models := make([]ListModelResponse, 0) | |
| for _, model := range result["data"].([]interface{}) { | |
| modelMap := model.(map[string]interface{}) | |
| modelName := modelMap["id"].(string) | |
| models = append(models, modelName) | |
| models = append(models, ListModelResponse{Name: modelName}) | |
| } | |
| models := make([]ListModelResponse, 0) | |
| data, ok := result["data"].([]interface{}) | |
| if !ok { | |
| return nil, fmt.Errorf("invalid data format in models list response") | |
| } | |
| for _, model := range data { | |
| modelMap, ok := model.(map[string]interface{}) | |
| if !ok { | |
| continue | |
| } | |
| modelName, ok := modelMap["id"].(string) | |
| if !ok || modelName == "" { | |
| continue | |
| } | |
| models = append(models, ListModelResponse{Name: 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/lmstudio.go` around lines 564 - 569, The loop building
models from result uses unchecked type assertions and can panic; update the code
that constructs the []ListModelResponse from result to first verify
result["data"] is a []interface{} (using the comma-ok/type switch), then for
each element assert it is a map[string]interface{} and that map["id"] is a
string (using comma-ok), skipping or logging entries that fail validation
instead of panicking; keep the output type as []ListModelResponse and only
append valid Name values to models to preserve existing behavior.
| for _, model := range result["models"].([]interface{}) { | ||
| modelMap := model.(map[string]interface{}) | ||
| modelName := modelMap["name"].(string) | ||
| models = append(models, modelName) | ||
| models = append(models, ListModelResponse{Name: modelName}) | ||
| } |
There was a problem hiding this comment.
Unsafe type assertions can panic on unexpected API responses.
Lines 519-521 use direct type assertions without checking the ok return value. If the Ollama API returns an unexpected format (e.g., models is nil, or entries have different structure), this will cause a runtime panic.
Other drivers in this PR (novita, nvidia, openai) correctly use safe type assertions with ok checks.
🛡️ Proposed fix using safe type assertions
// convert result["data"] to []map[string]interface{}
models := make([]ListModelResponse, 0)
- for _, model := range result["models"].([]interface{}) {
- modelMap := model.(map[string]interface{})
- modelName := modelMap["name"].(string)
+ modelsList, ok := result["models"].([]interface{})
+ if !ok {
+ return nil, fmt.Errorf("invalid models list format")
+ }
+ for _, model := range modelsList {
+ modelMap, ok := model.(map[string]interface{})
+ if !ok {
+ continue
+ }
+ modelName, ok := modelMap["name"].(string)
+ if !ok {
+ continue
+ }
models = append(models, ListModelResponse{Name: 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.
| for _, model := range result["models"].([]interface{}) { | |
| modelMap := model.(map[string]interface{}) | |
| modelName := modelMap["name"].(string) | |
| models = append(models, modelName) | |
| models = append(models, ListModelResponse{Name: modelName}) | |
| } | |
| // convert result["data"] to []map[string]interface{} | |
| models := make([]ListModelResponse, 0) | |
| modelsList, ok := result["models"].([]interface{}) | |
| if !ok { | |
| return nil, fmt.Errorf("invalid models list format") | |
| } | |
| for _, model := range modelsList { | |
| modelMap, ok := model.(map[string]interface{}) | |
| if !ok { | |
| continue | |
| } | |
| modelName, ok := modelMap["name"].(string) | |
| if !ok { | |
| continue | |
| } | |
| models = append(models, ListModelResponse{Name: 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/ollama.go` around lines 519 - 523, The loop over
result["models"] in ollama.go uses unsafe type assertions and can panic; update
the code that iterates over result["models"] to use safe type assertions (check
ok when casting result["models"] to []interface{} and when casting each model to
map[string]interface{} and the "name" field to string), skip entries that fail
casts instead of panicking, and append valid names to ListModelResponse{Name:
...}; ensure you reference the existing variables/result map and the
ListModelResponse type so behavior stays consistent with other drivers (novita,
nvidia, openai).
| models := make([]ListModelResponse, 0) | ||
| for _, model := range result["data"].([]interface{}) { | ||
| modelMap := model.(map[string]interface{}) | ||
| modelName := modelMap["id"].(string) | ||
| models = append(models, modelName) | ||
| models = append(models, ListModelResponse{Name: modelName}) | ||
| } |
There was a problem hiding this comment.
Unsafe type assertions can cause runtime panic.
Lines 796-798 perform type assertions without checking the ok result. If the OpenRouter API returns an unexpected response format, these will panic at runtime.
🛡️ Suggested fix to add safety checks
// convert result["data"] to []map[string]interface{}
models := make([]ListModelResponse, 0)
- for _, model := range result["data"].([]interface{}) {
- modelMap := model.(map[string]interface{})
- modelName := modelMap["id"].(string)
+ data, ok := result["data"].([]interface{})
+ if !ok {
+ return nil, fmt.Errorf("invalid response format: data field is not an array")
+ }
+ for _, model := range data {
+ modelMap, ok := model.(map[string]interface{})
+ if !ok {
+ continue
+ }
+ modelName, ok := modelMap["id"].(string)
+ if !ok || modelName == "" {
+ continue
+ }
models = append(models, ListModelResponse{Name: 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/openrouter.go` around lines 795 - 800, The loop
building models from result["data"] uses unchecked type assertions and can
panic; update the code that iterates over result["data"] to safely assert types
(check ok values) for the top-level slice, each element being a
map[string]interface{}, and the "id" field being a string before using them
(symbols: result, models, ListModelResponse, modelMap, modelName); skip or log
invalid entries instead of asserting, and only append ListModelResponse{Name:
modelName} when all assertions succeed.
| models := make([]ListModelResponse, 0) | ||
| for _, model := range result["data"].([]interface{}) { | ||
| modelMap := model.(map[string]interface{}) | ||
| modelName := modelMap["id"].(string) | ||
| models = append(models, modelName) | ||
| models = append(models, ListModelResponse{Name: modelName}) | ||
| } |
There was a problem hiding this comment.
Unsafe type assertions can cause runtime panic.
Lines 468-470 perform type assertions without checking the ok result. If the OrcaRouter API returns an unexpected response format, these will panic at runtime.
🛡️ Suggested fix to add safety checks
// convert result["data"] to []map[string]interface{}
models := make([]ListModelResponse, 0)
- for _, model := range result["data"].([]interface{}) {
- modelMap := model.(map[string]interface{})
- modelName := modelMap["id"].(string)
+ data, ok := result["data"].([]interface{})
+ if !ok {
+ return nil, fmt.Errorf("invalid response format: data field is not an array")
+ }
+ for _, model := range data {
+ modelMap, ok := model.(map[string]interface{})
+ if !ok {
+ continue
+ }
+ modelName, ok := modelMap["id"].(string)
+ if !ok || modelName == "" {
+ continue
+ }
models = append(models, ListModelResponse{Name: 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/orcarouter.go` around lines 467 - 472, The loop
blindly type-asserts result["data"] and each model to concrete types which can
panic; change the parsing in the ListModelResponse construction to perform safe
type checks (use a type assertion with the "ok" idiom or a type switch) for
result["data"] to ensure it's a []interface{}, for each model to ensure it's a
map[string]interface{}, and for the "id" field to ensure it's a string, skip or
log entries that fail validation instead of asserting; update the block that
builds models (references: result, models, modelMap, modelName,
ListModelResponse) to only append when all checks succeed.
| models := make([]ListModelResponse, 0) | ||
| for _, model := range result["data"].([]interface{}) { | ||
| modelMap := model.(map[string]interface{}) | ||
| modelName := modelMap["id"].(string) | ||
| models = append(models, modelName) | ||
| models = append(models, ListModelResponse{Name: modelName}) |
There was a problem hiding this comment.
Guard ListModels response parsing against panics.
These hard assertions will panic if the upstream payload shape changes (or returns an error object with HTTP 200). Convert them to checked assertions and return an error instead.
Proposed fix
- models := make([]ListModelResponse, 0)
- for _, model := range result["data"].([]interface{}) {
- modelMap := model.(map[string]interface{})
- modelName := modelMap["id"].(string)
- models = append(models, ListModelResponse{Name: modelName})
- }
+ rawData, ok := result["data"].([]interface{})
+ if !ok {
+ return nil, fmt.Errorf("invalid models response: missing/invalid data field")
+ }
+ models := make([]ListModelResponse, 0, len(rawData))
+ for _, item := range rawData {
+ modelMap, ok := item.(map[string]interface{})
+ if !ok {
+ return nil, fmt.Errorf("invalid models response: invalid model item")
+ }
+ modelName, ok := modelMap["id"].(string)
+ if !ok || strings.TrimSpace(modelName) == "" {
+ continue
+ }
+ models = append(models, ListModelResponse{Name: 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.
| models := make([]ListModelResponse, 0) | |
| for _, model := range result["data"].([]interface{}) { | |
| modelMap := model.(map[string]interface{}) | |
| modelName := modelMap["id"].(string) | |
| models = append(models, modelName) | |
| models = append(models, ListModelResponse{Name: modelName}) | |
| rawData, ok := result["data"].([]interface{}) | |
| if !ok { | |
| return nil, fmt.Errorf("invalid models response: missing/invalid data field") | |
| } | |
| models := make([]ListModelResponse, 0, len(rawData)) | |
| for _, item := range rawData { | |
| modelMap, ok := item.(map[string]interface{}) | |
| if !ok { | |
| return nil, fmt.Errorf("invalid models response: invalid model item") | |
| } | |
| modelName, ok := modelMap["id"].(string) | |
| if !ok || strings.TrimSpace(modelName) == "" { | |
| continue | |
| } | |
| models = append(models, ListModelResponse{Name: 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/xunfei.go` around lines 439 - 443, In ListModels,
avoid unchecked type assertions on result["data"] and its elements (currently
producing modelMap := model.(map[string]interface{}) and
modelMap["id"].(string)); instead validate types with comma-ok checks and return
a descriptive error if the payload shape is unexpected (e.g., ensure
result["data"] exists and is []interface{}, each item is map[string]interface{},
and "id" is a string) before appending to the models slice (ListModelResponse);
update error handling to propagate a clear error rather than allowing a panic.
| var result []map[string]interface{} | ||
| for _, model := range modelList { | ||
| result = append(result, map[string]interface{}{ | ||
| "name": model.Name, | ||
| "dimension": model.Dimension, | ||
| "max_tokens": model.MaxTokens, | ||
| "model_types": model.ModelTypes, | ||
| "thinking": model.Thinking, | ||
| }) | ||
| } | ||
| return result, nil |
There was a problem hiding this comment.
Return an empty array (not null) for empty supported-model results.
When no models are returned, this stays nil and is serialized as null. Initialize the slice to preserve a stable array response contract.
Proposed fix
- var result []map[string]interface{}
+ result := make([]map[string]interface{}, 0, len(modelList))
for _, model := range modelList {
result = append(result, map[string]interface{}{
"name": model.Name,
"dimension": model.Dimension,
"max_tokens": model.MaxTokens,
"model_types": model.ModelTypes,
"thinking": model.Thinking,
})
}📝 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.
| var result []map[string]interface{} | |
| for _, model := range modelList { | |
| result = append(result, map[string]interface{}{ | |
| "name": model.Name, | |
| "dimension": model.Dimension, | |
| "max_tokens": model.MaxTokens, | |
| "model_types": model.ModelTypes, | |
| "thinking": model.Thinking, | |
| }) | |
| } | |
| return result, nil | |
| result := make([]map[string]interface{}, 0, len(modelList)) | |
| for _, model := range modelList { | |
| result = append(result, map[string]interface{}{ | |
| "name": model.Name, | |
| "dimension": model.Dimension, | |
| "max_tokens": model.MaxTokens, | |
| "model_types": model.ModelTypes, | |
| "thinking": model.Thinking, | |
| }) | |
| } | |
| return result, 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 247 - 257, The slice result
is left nil when modelList is empty, causing JSON serialization to emit null;
initialize result as an empty slice (e.g. result :=
make([]map[string]interface{}, 0)) before the loop that iterates modelList so
you always return an empty array instead of nil from the function that builds
maps from model.Name, model.Dimension, model.MaxTokens, model.ModelTypes,
model.Thinking.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15845 +/- ##
=======================================
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:
|
What problem does this PR solve?
Now list supported models will show more info.
Type of change