Repository navigation
fix(Go): rewrite chat, listmodels, embed for Ollama - #15213
Conversation
📝 WalkthroughWalkthroughOllama and Xinference model provider configurations are updated with new endpoint mappings. The Ollama provider implementation is refactored to support multimodal message formats, simplified thinking controls, and Ollama-native response structures across chat, streaming, embedding, and model listing operations. ChangesOllama Provider Configuration and Implementation Updates
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 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: 4
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
internal/entity/models/ollama.go (2)
199-202:⚠️ Potential issue | 🟠 Major | ⚡ Quick winInconsistent model name splitting between chat functions.
ChatWithMessages(line 72) splits on"_"whileChatStreamlyWithSendersplits on"-". This inconsistency means theqwen/glmasync endpoint logic may trigger for one function but not the other with the same model name (e.g.,qwen-3vsqwen_3).- modelType := strings.Split(modelName, "-")[0] + modelType := strings.Split(modelName, "_")[0]🤖 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 199 - 202, The model-name parsing is inconsistent between ChatWithMessages and ChatStreamlyWithSender (one splits on "_" while the other splits on "-"), causing incorrect detection of qwen/glm models; update the parsing in internal/entity/models/ollama.go so both functions use the same logic — e.g., normalize modelName or split on both '-' and '_' (or use strings.FieldsFunc to treat either separator the same) before checking if modelType == "qwen" || modelType == "glm", and apply the same change to the ChatWithMessages and ChatStreamlyWithSender code paths.
226-258:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winMissing nil check for
modelConfigcauses panic.Unlike
ChatWithMessages(line 100), this function accessesmodelConfigfields without first checking ifmodelConfigis nil. If a caller passesnil, this will panic.🛡️ Proposed fix
+ if modelConfig != nil { if modelConfig.Stream != nil { reqBody["stream"] = *modelConfig.Stream } if modelConfig.MaxTokens != nil { reqBody["max_tokens"] = *modelConfig.MaxTokens } // ... rest of the config handling ... } + }Wrap lines 226-258 in a
if modelConfig != nilblock.🤖 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 226 - 258, The code accesses fields on modelConfig without verifying it's non-nil, which can panic; update the function containing this block to first check if modelConfig != nil and only then execute the series of conditionals that set reqBody ("stream", "max_tokens", "temperature", "do_sample", "top_p", "stop", "effort"/"think") and the strings.HasPrefix(modelName, "gpt-oss") branch so all uses of modelConfig are guarded; locate the block referencing modelConfig and modelName (the ifs that set reqBody keys and the think/effort logic) and wrap them in a single if modelConfig != nil { ... }.
🧹 Nitpick comments (1)
internal/entity/models/ollama.go (1)
468-480: 💤 Low valueUnnecessary request body for GET request.
GET requests typically don't include a body. The empty
reqBodymarshaling andContent-Typeheader are unnecessary overhead.♻️ Suggested simplification
- reqBody := map[string]interface{}{} - - jsonData, err := json.Marshal(reqBody) - if err != nil { - return nil, fmt.Errorf("failed to marshal request: %w", err) - } - - req, err := http.NewRequest("GET", url, bytes.NewBuffer(jsonData)) + req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, fmt.Errorf("failed to create request: %w", err) } - - req.Header.Set("Content-Type", "application/json")🤖 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 468 - 480, Remove the unnecessary empty request body creation and Content-Type header for the GET request: eliminate the reqBody map, json.Marshal(reqBody) and bytes.NewBuffer(jsonData), and construct the request with http.NewRequest("GET", url, nil) instead of passing a body; also remove the req.Header.Set("Content-Type", \"application/json\") call since GET should not send a JSON body. Use the existing variables req, err and the same error handling around http.NewRequest to keep behavior consistent.
🤖 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/models/ollama.json`:
- Around line 4-6: The config key "models" in conf/models/ollama.json currently
points to Ollama's /api/ps which only returns running models; change the
"models" value from "api/ps" to "api/tags" so the app will use the endpoint that
lists all locally available/downloaded models (leave "chat" and "embedding"
as-is). Ensure the string is updated in the "models" property in
conf/models/ollama.json and verify any code reading that key expects the
/api/tags response format.
In `@internal/entity/models/ollama.go`:
- Around line 80-88: Guard against panics when converting msg.Content to a
[]interface{} and extracting text: in the loop that builds apiMessages use safe
type checks (type switch or ok-style assertions) on msg.Content, handle cases
where msg.Content is a string, nil, or not a slice, check arr length before
accessing arr[0], and verify first is a map[string]interface{} and that
first["text"] is a string before assigning to text; if any check fails, set text
to an empty string (or a safe default) and still populate apiMessages[i] with
{"role": msg.Role, "content": text} so unexpected message formats do not cause
index or type-panics.
- Around line 175-178: The parsing logic in the function that reads Ollama
responses (the code assigning reasonContent from message["thinking"]) is too
strict—change it so the "thinking" field is optional: check if
message["thinking"] exists and is a string before casting, and only return an
error if some other required field is missing; otherwise set a zero-value (e.g.,
empty string or nil) for reasonContent and continue. Update the block that
currently does reasonContent, ok := message["thinking"].(string) and the
subsequent error return to conditionally handle absent/non-string "thinking"
without failing the whole response parse.
- Around line 505-508: The loop blindly type-asserts result["models"] and its
elements which can panic; change the code that builds the models slice to first
check that result["models"] is present and is a []interface{} (use the ok comma
pattern), then for each element ensure it's a map[string]interface{} before
accessing "name", and ensure the "name" value is a string (again using ok
checks) before appending to models; skip or log invalid entries rather than
panicking (references: the variables result, models, modelMap, modelName in the
existing loop).
---
Outside diff comments:
In `@internal/entity/models/ollama.go`:
- Around line 199-202: The model-name parsing is inconsistent between
ChatWithMessages and ChatStreamlyWithSender (one splits on "_" while the other
splits on "-"), causing incorrect detection of qwen/glm models; update the
parsing in internal/entity/models/ollama.go so both functions use the same logic
— e.g., normalize modelName or split on both '-' and '_' (or use
strings.FieldsFunc to treat either separator the same) before checking if
modelType == "qwen" || modelType == "glm", and apply the same change to the
ChatWithMessages and ChatStreamlyWithSender code paths.
- Around line 226-258: The code accesses fields on modelConfig without verifying
it's non-nil, which can panic; update the function containing this block to
first check if modelConfig != nil and only then execute the series of
conditionals that set reqBody ("stream", "max_tokens", "temperature",
"do_sample", "top_p", "stop", "effort"/"think") and the
strings.HasPrefix(modelName, "gpt-oss") branch so all uses of modelConfig are
guarded; locate the block referencing modelConfig and modelName (the ifs that
set reqBody keys and the think/effort logic) and wrap them in a single if
modelConfig != nil { ... }.
---
Nitpick comments:
In `@internal/entity/models/ollama.go`:
- Around line 468-480: Remove the unnecessary empty request body creation and
Content-Type header for the GET request: eliminate the reqBody map,
json.Marshal(reqBody) and bytes.NewBuffer(jsonData), and construct the request
with http.NewRequest("GET", url, nil) instead of passing a body; also remove the
req.Header.Set("Content-Type", \"application/json\") call since GET should not
send a JSON body. Use the existing variables req, err and the same error
handling around http.NewRequest to keep behavior consistent.
🪄 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: 7021e3c7-229e-4286-801f-d948a28d5b0f
📒 Files selected for processing (3)
conf/models/ollama.jsonconf/models/xinference.jsoninternal/entity/models/ollama.go
| "chat": "api/chat", | ||
| "models": "api/ps", | ||
| "embedding": "api/embed" |
There was a problem hiding this comment.
🧩 Analysis chain
🌐 Web query:
Ollama API endpoint to list all models api/tags vs api/ps
💡 Result:
Use: 1) List all locally available (downloaded) models - Endpoint: GET /api/tags [1] - Example: curl http://localhost:11434/api/tags [1] 2) List models that are currently running (loaded into memory) - Endpoint: GET /api/ps [2] - Example: curl http://localhost:11434/api/ps [2] Difference in meaning - /api/tags “List models” returns all locally available models on the local system [1]. - /api/ps “List running models” returns models currently loaded into memory [2].
Citations:
- 1: https://docs.ollama.com/api/tags
- 2: https://docs.ollama.com/api/ps
🌐 Web query:
Ollama native chat endpoint POST /api/chat and embedding endpoint /api/embed (vs /api/embeddings)
💡 Result:
Ollama provides specific REST API endpoints for chat and embedding operations. POST /api/chat The /api/chat endpoint is the standard, native Ollama API for generating chat completions [1][2][3]. It supports streaming responses by default, which can be disabled by setting the stream parameter to false [2][3]. This endpoint accepts a model name and a list of messages (with roles such as system, user, assistant, or tool) to maintain conversation history [2][3]. It also supports advanced features like tool calling and thinking models [2][3]. /api/embed vs. /api/embeddings The /api/embed endpoint is the current, official native API for generating text embeddings [4][5]. It supports both single strings and batches of strings via the input parameter [4]. The /api/embeddings endpoint is deprecated [6][7][8]. Users should migrate to /api/embed for native embedding tasks [6][9]. If your application requires OpenAI-compatible embedding support, you should use the /v1/embeddings endpoint instead, which is part of Ollama's OpenAI-compatible API layer [8]. Summary of API Usage - For native chat: Use POST /api/chat [1][3]. - For native embeddings: Use POST /api/embed [4][5]. - For OpenAI-compatible integrations: Use the /v1/ path (e.g., /v1/chat/completions or /v1/embeddings) [10][8][11].
Citations:
- 1: https://docs.ollama.com/api/chat
- 2: https://github.com/ollama/ollama/blob/cb003359/docs/api.md
- 3: https://github.com/ollama/ollama/blob/main/docs/api.md
- 4: https://docs.ollama.com/capabilities/embeddings
- 5: https://docs.ollama.com/api/embed
- 6: /api/embeddings returning 404 ollama/ollama#6533
- 7: Introduce
/api/embedendpoint supporting batch embedding ollama/ollama#5127 - 8:
api/embedendpoint is not working exactly likeapi/embeddingsendpoint ollama/ollama#7242 - 9: https://www.reddit.com/r/ollama/comments/1ghcsbi/python_library_embeddings_vs_embed_functions/
- 10: https://dev.to/lingdas1/production-ready-local-llms-from-terminal-to-team-deployment-4ph2
- 11: https://dev.to/yann_ortodoro/running-qwen-25-coder-14b-locally-in-cursor-with-ollama-4436
Fix model listing endpoint: /api/ps vs /api/tags in conf/models/ollama.json
"chat": "api/chat",
"models": "api/ps",
"embedding": "api/embed"
"models": "api/ps" uses Ollama’s /api/ps, which returns only currently running/loaded models; /api/tags is the endpoint for listing all locally available (downloaded) models. If this config is meant to populate a full model list (including not-yet-running models), switch "models" to api/tags. (api/chat and api/embed are the correct native endpoints.)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@conf/models/ollama.json` around lines 4 - 6, The config key "models" in
conf/models/ollama.json currently points to Ollama's /api/ps which only returns
running models; change the "models" value from "api/ps" to "api/tags" so the app
will use the endpoint that lists all locally available/downloaded models (leave
"chat" and "embedding" as-is). Ensure the string is updated in the "models"
property in conf/models/ollama.json and verify any code reading that key expects
the /api/tags response format.
| arr, _ := msg.Content.([]interface{}) | ||
|
|
||
| first, _ := arr[0].(map[string]interface{}) | ||
|
|
||
| text, _ := first["text"].(string) | ||
|
|
||
| apiMessages[i] = map[string]interface{}{ | ||
| "role": msg.Role, | ||
| "content": msg.Content, | ||
| "content": text, |
There was a problem hiding this comment.
Unchecked type assertions will panic on unexpected message formats.
The code assumes msg.Content is always a non-empty []interface{} containing maps with a "text" key. If Content is a plain string, nil, or an empty array, this will panic:
- Line 80: If
msg.Contentis not[]interface{},arrisnil - Line 82: If
arris empty or nil,arr[0]causes index out of range panic - Lines 82, 84: Unchecked type assertions can also panic
🛡️ Proposed defensive fix
- arr, _ := msg.Content.([]interface{})
-
- first, _ := arr[0].(map[string]interface{})
-
- text, _ := first["text"].(string)
+ var text string
+ switch v := msg.Content.(type) {
+ case string:
+ text = v
+ case []interface{}:
+ if len(v) > 0 {
+ if first, ok := v[0].(map[string]interface{}); ok {
+ text, _ = first["text"].(string)
+ }
+ }
+ }📝 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.
| arr, _ := msg.Content.([]interface{}) | |
| first, _ := arr[0].(map[string]interface{}) | |
| text, _ := first["text"].(string) | |
| apiMessages[i] = map[string]interface{}{ | |
| "role": msg.Role, | |
| "content": msg.Content, | |
| "content": text, | |
| var text string | |
| switch v := msg.Content.(type) { | |
| case string: | |
| text = v | |
| case []interface{}: | |
| if len(v) > 0 { | |
| if first, ok := v[0].(map[string]interface{}); ok { | |
| text, _ = first["text"].(string) | |
| } | |
| } | |
| } | |
| apiMessages[i] = map[string]interface{}{ | |
| "role": msg.Role, | |
| "content": text, |
🤖 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 80 - 88, Guard against panics
when converting msg.Content to a []interface{} and extracting text: in the loop
that builds apiMessages use safe type checks (type switch or ok-style
assertions) on msg.Content, handle cases where msg.Content is a string, nil, or
not a slice, check arr length before accessing arr[0], and verify first is a
map[string]interface{} and that first["text"] is a string before assigning to
text; if any check fails, set text to an empty string (or a safe default) and
still populate apiMessages[i] with {"role": msg.Role, "content": text} so
unexpected message formats do not cause index or type-panics.
| for _, model := range result["models"].([]interface{}) { | ||
| modelMap := model.(map[string]interface{}) | ||
| modelName := modelMap["id"].(string) | ||
| modelName := modelMap["name"].(string) | ||
| models = append(models, modelName) |
There was a problem hiding this comment.
Unchecked type assertions will panic if response format differs.
If result["models"] is nil or not the expected type, the type assertion on line 505 will panic. Similarly for the nested assertions on lines 506-507.
🛡️ Proposed defensive fix
models := make([]string, 0)
- for _, model := range result["models"].([]interface{}) {
- modelMap := model.(map[string]interface{})
- modelName := modelMap["name"].(string)
- models = append(models, modelName)
+ modelList, ok := result["models"].([]interface{})
+ if !ok {
+ return nil, fmt.Errorf("failed to parse response: models field not found or invalid")
+ }
+ for _, model := range modelList {
+ modelMap, ok := model.(map[string]interface{})
+ if !ok {
+ continue
+ }
+ if modelName, ok := modelMap["name"].(string); ok {
+ models = append(models, 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["id"].(string) | |
| modelName := modelMap["name"].(string) | |
| models = append(models, modelName) | |
| modelList, ok := result["models"].([]interface{}) | |
| if !ok { | |
| return nil, fmt.Errorf("failed to parse response: models field not found or invalid") | |
| } | |
| for _, model := range modelList { | |
| modelMap, ok := model.(map[string]interface{}) | |
| if !ok { | |
| continue | |
| } | |
| if modelName, ok := modelMap["name"].(string); ok { | |
| models = append(models, 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 505 - 508, The loop blindly
type-asserts result["models"] and its elements which can panic; change the code
that builds the models slice to first check that result["models"] is present and
is a []interface{} (use the ok comma pattern), then for each element ensure it's
a map[string]interface{} before accessing "name", and ensure the "name" value is
a string (again using ok checks) before appending to models; skip or log invalid
entries rather than panicking (references: the variables result, models,
modelMap, modelName in the existing loop).
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15213 +/- ##
=======================================
Coverage 93.12% 93.12%
=======================================
Files 10 10
Lines 713 713
Branches 116 116
=======================================
Hits 664 664
Misses 29 29
Partials 20 20 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
What problem does this PR solve?
IDK how to implement
Ollamaon #14580 but it's totally wrong.This is the rewrite version for
OllamaVerified from CLI
Type of change