Repository navigation
Go: implement provider: Ollama - #14580
Conversation
📝 WalkthroughWalkthroughThis pull request adds Ollama as a new local model provider with full chat and streaming capabilities, adjusts Moonshot's default temperature from 1 to 0.6, removes the deprecated Chat method from VllmModel, and adds corresponding Ollama configuration. ChangesOllama Model Provider Integration
Model Configuration & Interface Refinements
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes 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: 7
🧹 Nitpick comments (2)
internal/entity/models/ollama.go (2)
88-92: 💤 Low valueHard-coded default
temperature: 1is overridden later — but worth aligning with Moonshot's recent change.This PR drops Moonshot's default from
1→0.6; the new Ollama provider initialises with1and is overwritten only whenchatModelConfig != nil && chatModelConfig.Temperature != nil. If the rationale for the Moonshot change applies here too, consider matching it; otherwise document why Ollama keeps1.🤖 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 88 - 92, The Ollama request payload currently hard-codes "temperature": 1 which is later only overridden when chatModelConfig != nil && chatModelConfig.Temperature != nil; update the default to match Moonshot's new default by changing the initial "temperature" value from 1 to 0.6 in the Ollama payload (the map containing "model", "messages", "stream", "temperature"), or alternatively add a brief comment explaining why Ollama intentionally uses 1 if you decide to keep it; ensure the logic around chatModelConfig.Temperature remains unchanged.
39-57: 💤 Low valueReceiver type inconsistency.
Constructor
NewOllamaModelreturns*OllamaModel, but every method (NewInstance,Name,ChatWithMessages,ChatStreamlyWithSender, …) is declared on the value receivero OllamaModel. This deviates fromMoonshotModel(pointer receivers) and means each call copies the struct including the*http.Clientpointer. While interface satisfaction still works becauseNewOllamaModelreturns a pointer, mixing receiver kinds across the codebase is a known idiomatic smell in Go and complicates future state-bearing extensions (e.g., adding mutexes/caches toOllamaModel).♻️ Proposed alignment with MoonshotModel
-func (o OllamaModel) NewInstance(baseURL map[string]string) ModelDriver { +func (o *OllamaModel) NewInstance(baseURL map[string]string) ModelDriver { @@ -func (o OllamaModel) Name() string { +func (o *OllamaModel) Name() string { @@ -func (o OllamaModel) ChatWithMessages(... +func (o *OllamaModel) ChatWithMessages(...(apply the same to all other methods)
🤖 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 39 - 57, The OllamaModel methods currently use a value receiver (e.g., func (o OllamaModel) NewInstance(...) and func (o OllamaModel) Name()) which causes copies of the struct (including the *http.Client) and is inconsistent with MoonshotModel; change all methods on OllamaModel—NewInstance, Name, ChatWithMessages, ChatStreamlyWithSender, etc.—to use a pointer receiver (func (o *OllamaModel) ...) so the type is consistently pointer-receiver based, avoid copying internal fields, and align with NewOllamaModel which returns *OllamaModel.
🤖 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 3-6: The config is missing the async_chat URL suffix used by
OllamaModel (referenced as o.URLSuffix.AsyncChat in
internal/entity/models/ollama.go); add an "async_chat" entry alongside "chat"
and "models" in conf/models/ollama.json (e.g., "async_chat": "chat/completions"
or the correct Ollama async path) so the AsyncChat branch resolves to a valid
URL, or alternatively remove/disable the AsyncChat branch in OllamaModel if you
intend to rely solely on the OpenAI-compatible endpoint.
In `@internal/entity/models/ollama.go`:
- Around line 285-295: The SSE loop using bufio.NewScanner on resp.Body can
overflow the default 64KiB token size and is logging every raw SSE line at info
level; update the streaming loop in the Ollama SSE reader (the scanner usage
handling resp.Body) to either set a larger scanner buffer via
scanner.Buffer(make([]byte,0,64*1024), 1024*1024) or replace the scanner with a
bufio.Reader and use ReadBytes('\n') to avoid bufio.ErrTooLong, and
change/remove the common.Info(line) call so raw SSE chunks are not logged at
info level (use common.Debug or drop logging) — apply the same change pattern to
MoonshotModel.ChatStreamlyWithSender where the same scanner/logging pattern is
used.
- Around line 138-139: The Authorization header is being set unconditionally
using *apiConfig.ApiKey which can be nil for local Ollama deployments and causes
a panic; update the three call sites (ChatWithMessages, ChatStreamlyWithSender,
and ListModels) to only set the Authorization header when apiConfig.ApiKey is
non-nil and non-empty (e.g., check apiConfig.ApiKey != nil && *apiConfig.ApiKey
!= ""), mirroring the conditional guard used in moonshot.go, and leave the
Content-Type header unchanged.
- Around line 421-423: OllamaModel.CheckConnection currently always returns a
hard-coded error, preventing successful health checks; update
OllamaModel.CheckConnection to mirror MoonshotModel.CheckConnection by calling
the provider's ListModels method (e.g., o.ListModels or the equivalent method
used on OllamaModel) and returning nil if ListModels succeeds or returning the
encountered error if it fails, so the connectivity check reflects the real
provider response.
- Around line 94-190: The code allows chatModelConfig to be nil but later
dereferences it in GetThinkingAndAnswer(chatModelConfig.ModelClass, &content),
which can panic; fix by introducing a nil-safe modelClass variable (e.g.,
modelClass := "" or a sensible default) and set modelClass =
chatModelConfig.ModelClass only if chatModelConfig != nil, then call
GetThinkingAndAnswer(modelClass, &content). Also add a nil guard in
ChatStreamlyWithSender to avoid dereferencing modelConfig (check modelConfig !=
nil before accessing modelConfig.Stream, modelConfig.MaxTokens,
modelConfig.Temperature, modelConfig.TopP, modelConfig.Stop,
modelConfig.Thinking or document/require non-nil in the function contract).
- Around line 64-75: Fix three issues in endpoint selection in
MoonshotModel.ChatWithMessages/ChatStreamlyWithSender: 1) use a consistent
separator (use "-" since model names like "qwen-2.5" use hyphens) when computing
modelType (replace strings.Split(modelName, "_") with the hyphen-based split
logic used elsewhere) so both branches behave the same; 2) remove or disable the
AsyncChat branch for Ollama (o.URLSuffix.AsyncChat) because
conf/models/ollama.json does not define async_chat and will produce a trailing
slash/404—use o.URLSuffix.Chat only for Ollama or check that
o.URLSuffix.AsyncChat is non-empty before switching; 3) guard dereferencing
apiConfig.Region by checking apiConfig != nil && apiConfig.Region != nil before
using *apiConfig.Region (mirror the nil-check pattern used in
MoonshotModel.ChatWithMessages) so passing a nil apiConfig does not panic.
- Around line 361-415: In OllamaModel.ListModels: remove the unnecessary JSON
body for the GET (stop marshalling reqBody and call http.NewRequest("GET", url,
nil) instead), and replace all unchecked assertions when parsing result (result,
result["data"], each model element and modelMap["id"]) with two-value type
checks (v, ok := ...) and return clear errors when types/keys are missing;
specifically validate result is map[string]interface{}, result["data"] is
[]interface{}, each item is map[string]interface{}, and the "id" is a string
before appending to models to avoid panics.
---
Nitpick comments:
In `@internal/entity/models/ollama.go`:
- Around line 88-92: The Ollama request payload currently hard-codes
"temperature": 1 which is later only overridden when chatModelConfig != nil &&
chatModelConfig.Temperature != nil; update the default to match Moonshot's new
default by changing the initial "temperature" value from 1 to 0.6 in the Ollama
payload (the map containing "model", "messages", "stream", "temperature"), or
alternatively add a brief comment explaining why Ollama intentionally uses 1 if
you decide to keep it; ensure the logic around chatModelConfig.Temperature
remains unchanged.
- Around line 39-57: The OllamaModel methods currently use a value receiver
(e.g., func (o OllamaModel) NewInstance(...) and func (o OllamaModel) Name())
which causes copies of the struct (including the *http.Client) and is
inconsistent with MoonshotModel; change all methods on OllamaModel—NewInstance,
Name, ChatWithMessages, ChatStreamlyWithSender, etc.—to use a pointer receiver
(func (o *OllamaModel) ...) so the type is consistently pointer-receiver based,
avoid copying internal fields, and align with NewOllamaModel which returns
*OllamaModel.
🪄 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: 66837e20-82ad-4eab-9914-8efe6339e85b
📒 Files selected for processing (4)
conf/models/ollama.jsoninternal/entity/models/moonshot.gointernal/entity/models/ollama.gointernal/entity/models/vllm.go
💤 Files with no reviewable changes (1)
- internal/entity/models/vllm.go
| "url_suffix": { | ||
| "chat": "chat/completions", | ||
| "models": "models" | ||
| }, |
There was a problem hiding this comment.
Missing async_chat URL suffix referenced by OllamaModel.
internal/entity/models/ollama.go (lines 73‑75 and 204‑206) routes qwen/glm models to o.URLSuffix.AsyncChat, but this config only defines chat and models. For those model families the resulting URL becomes <base>/ (empty suffix), producing a 404 against any real Ollama server. Either add an async_chat entry here or drop the AsyncChat branch in the Go code (Ollama's OpenAI-compatible API does not have a separate async endpoint anyway).
📝 Proposed fix (if AsyncChat is intended)
"url_suffix": {
"chat": "chat/completions",
+ "async_chat": "chat/completions",
"models": "models"
},🤖 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 3 - 6, The config is missing the
async_chat URL suffix used by OllamaModel (referenced as o.URLSuffix.AsyncChat
in internal/entity/models/ollama.go); add an "async_chat" entry alongside "chat"
and "models" in conf/models/ollama.json (e.g., "async_chat": "chat/completions"
or the correct Ollama async path) so the AsyncChat branch resolves to a valid
URL, or alternatively remove/disable the AsyncChat branch in OllamaModel if you
intend to rely solely on the OpenAI-compatible endpoint.
| var region = "default" | ||
| if apiConfig.Region != nil { | ||
| region = *apiConfig.Region | ||
| } | ||
|
|
||
| url := fmt.Sprintf("%s/%s", o.BaseURL[region], o.URLSuffix.Chat) | ||
|
|
||
| // For qwen/glm models, use async chat endpoint | ||
| modelType := strings.Split(modelName, "_")[0] | ||
| if modelType == "qwen" || modelType == "glm" { | ||
| url = fmt.Sprintf("%s/%s", o.BaseURL[region], o.URLSuffix.AsyncChat) | ||
| } |
There was a problem hiding this comment.
Two correctness bugs in endpoint selection.
- Inconsistent separator between sync and stream paths. Line 72 splits on
"_"while the streaming counterpart at line 203 splits on"-". Real model names use hyphens (qwen-2.5,glm-4), soChatWithMessageswill never take the AsyncChat branch whileChatStreamlyWithSenderwill. Pick one separator and apply it consistently. o.URLSuffix.AsyncChatis empty for Ollama. The companionconf/models/ollama.jsononly defineschatandmodels, so the AsyncChat branch produces a URL like<baseURL>/and the request 404s. Either defineasync_chatin the config or remove this branch entirely (Ollama's OpenAI-compatible surface has no async equivalent).apiConfig.Regionis dereferenced without checkingapiConfigitself for nil (MoonshotModel.ChatWithMessagesdoesapiConfig != nil && apiConfig.Region != nil). If a caller ever passesnil, this panics.
🐛 Proposed fix
- var region = "default"
- if apiConfig.Region != nil {
- region = *apiConfig.Region
- }
-
- url := fmt.Sprintf("%s/%s", o.BaseURL[region], o.URLSuffix.Chat)
-
- // For qwen/glm models, use async chat endpoint
- modelType := strings.Split(modelName, "_")[0]
- if modelType == "qwen" || modelType == "glm" {
- url = fmt.Sprintf("%s/%s", o.BaseURL[region], o.URLSuffix.AsyncChat)
- }
+ var region = "default"
+ if apiConfig != nil && apiConfig.Region != nil {
+ region = *apiConfig.Region
+ }
+
+ url := fmt.Sprintf("%s/%s", o.BaseURL[region], o.URLSuffix.Chat)And mirror the same change at lines 197‑206 (using "-" consistently if the AsyncChat branch is kept).
📝 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 region = "default" | |
| if apiConfig.Region != nil { | |
| region = *apiConfig.Region | |
| } | |
| url := fmt.Sprintf("%s/%s", o.BaseURL[region], o.URLSuffix.Chat) | |
| // For qwen/glm models, use async chat endpoint | |
| modelType := strings.Split(modelName, "_")[0] | |
| if modelType == "qwen" || modelType == "glm" { | |
| url = fmt.Sprintf("%s/%s", o.BaseURL[region], o.URLSuffix.AsyncChat) | |
| } | |
| var region = "default" | |
| if apiConfig != nil && apiConfig.Region != nil { | |
| region = *apiConfig.Region | |
| } | |
| url := fmt.Sprintf("%s/%s", o.BaseURL[region], o.URLSuffix.Chat) |
🤖 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 64 - 75, Fix three issues in
endpoint selection in MoonshotModel.ChatWithMessages/ChatStreamlyWithSender: 1)
use a consistent separator (use "-" since model names like "qwen-2.5" use
hyphens) when computing modelType (replace strings.Split(modelName, "_") with
the hyphen-based split logic used elsewhere) so both branches behave the same;
2) remove or disable the AsyncChat branch for Ollama (o.URLSuffix.AsyncChat)
because conf/models/ollama.json does not define async_chat and will produce a
trailing slash/404—use o.URLSuffix.Chat only for Ollama or check that
o.URLSuffix.AsyncChat is non-empty before switching; 3) guard dereferencing
apiConfig.Region by checking apiConfig != nil && apiConfig.Region != nil before
using *apiConfig.Region (mirror the nil-check pattern used in
MoonshotModel.ChatWithMessages) so passing a nil apiConfig does not panic.
| if chatModelConfig != nil { | ||
| if chatModelConfig.Stream != nil { | ||
| reqBody["stream"] = *chatModelConfig.Stream | ||
| } | ||
|
|
||
| if chatModelConfig.MaxTokens != nil { | ||
| reqBody["max_tokens"] = *chatModelConfig.MaxTokens | ||
| } | ||
|
|
||
| if chatModelConfig.Temperature != nil { | ||
| reqBody["temperature"] = *chatModelConfig.Temperature | ||
| } | ||
|
|
||
| if chatModelConfig.TopP != nil { | ||
| reqBody["top_p"] = *chatModelConfig.TopP | ||
| } | ||
|
|
||
| if chatModelConfig.Stop != nil { | ||
| reqBody["stop"] = *chatModelConfig.Stop | ||
| } | ||
|
|
||
| if chatModelConfig.Thinking != nil { | ||
| if *chatModelConfig.Thinking { | ||
| reqBody["thinking"] = map[string]interface{}{ | ||
| "type": "enabled", | ||
| } | ||
| } else { | ||
| reqBody["thinking"] = map[string]interface{}{ | ||
| "type": "disabled", | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| jsonData, err := json.Marshal(reqBody) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to marshal request: %w", err) | ||
| } | ||
|
|
||
| req, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(jsonData)) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to create request: %w", err) | ||
| } | ||
|
|
||
| req.Header.Set("Content-Type", "application/json") | ||
| req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) | ||
|
|
||
| resp, err := o.httpClient.Do(req) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to send request: %w", err) | ||
| } | ||
| defer resp.Body.Close() | ||
|
|
||
| body, err := io.ReadAll(resp.Body) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to read response body: %w", err) | ||
| } | ||
|
|
||
| if resp.StatusCode != http.StatusOK { | ||
| return nil, fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body)) | ||
| } | ||
|
|
||
| // Parse response | ||
| var result map[string]interface{} | ||
| if err = json.Unmarshal(body, &result); err != nil { | ||
| return nil, fmt.Errorf("failed to parse response: %w", err) | ||
| } | ||
|
|
||
| choices, ok := result["choices"].([]interface{}) | ||
| if !ok || len(choices) == 0 { | ||
| return nil, fmt.Errorf("no choices in response") | ||
| } | ||
|
|
||
| firstChoice, ok := choices[0].(map[string]interface{}) | ||
| if !ok { | ||
| return nil, fmt.Errorf("invalid choice format") | ||
| } | ||
|
|
||
| messageMap, ok := firstChoice["message"].(map[string]interface{}) | ||
| if !ok { | ||
| return nil, fmt.Errorf("invalid message format") | ||
| } | ||
|
|
||
| content, ok := messageMap["content"].(string) | ||
| if !ok { | ||
| return nil, fmt.Errorf("invalid content format") | ||
| } | ||
|
|
||
| thinking, answer := GetThinkingAndAnswer(chatModelConfig.ModelClass, &content) | ||
|
|
||
| chatResponse := &ChatResponse{ | ||
| Answer: answer, | ||
| ReasonContent: thinking, | ||
| } | ||
|
|
||
| return chatResponse, nil | ||
| } |
There was a problem hiding this comment.
chatModelConfig.ModelClass deref will panic when chatModelConfig is nil.
The function explicitly tolerates chatModelConfig == nil at line 94 (if chatModelConfig != nil { ... }), but then unconditionally dereferences it at line 182 via GetThinkingAndAnswer(chatModelConfig.ModelClass, &content). A caller that legitimately passes nil (allowed by the early guard) will crash here.
🐛 Proposed fix
- thinking, answer := GetThinkingAndAnswer(chatModelConfig.ModelClass, &content)
+ var modelClass string // or appropriate zero/default for ModelClass type
+ if chatModelConfig != nil {
+ modelClass = chatModelConfig.ModelClass
+ }
+ thinking, answer := GetThinkingAndAnswer(modelClass, &content)Note: ChatStreamlyWithSender has the symmetric issue — it dereferences modelConfig.Stream, modelConfig.MaxTokens, etc. at lines 224‑258 without ever checking modelConfig != nil. Please add a nil guard there as well (or document that the parameter is required and update the signature/contract accordingly).
🤖 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 94 - 190, The code allows
chatModelConfig to be nil but later dereferences it in
GetThinkingAndAnswer(chatModelConfig.ModelClass, &content), which can panic; fix
by introducing a nil-safe modelClass variable (e.g., modelClass := "" or a
sensible default) and set modelClass = chatModelConfig.ModelClass only if
chatModelConfig != nil, then call GetThinkingAndAnswer(modelClass, &content).
Also add a nil guard in ChatStreamlyWithSender to avoid dereferencing
modelConfig (check modelConfig != nil before accessing modelConfig.Stream,
modelConfig.MaxTokens, modelConfig.Temperature, modelConfig.TopP,
modelConfig.Stop, modelConfig.Thinking or document/require non-nil in the
function contract).
| req.Header.Set("Content-Type", "application/json") | ||
| req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) |
There was a problem hiding this comment.
Nil pointer deref on *apiConfig.ApiKey for a local provider.
Ollama is configured as "class": "local" and almost all real-world Ollama deployments have no API key set. With the current code, calling ChatWithMessages (line 139), ChatStreamlyWithSender (line 271), or ListModels (line 383) without an ApiKey panics with a nil-pointer dereference. Guard the header conditionally as Moonshot's non-streaming path does (lines 137‑139 of moonshot.go).
🛡️ Proposed fix (apply at all three sites)
req.Header.Set("Content-Type", "application/json")
- req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey))
+ if apiConfig != nil && apiConfig.ApiKey != nil && *apiConfig.ApiKey != "" {
+ req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey))
+ }📝 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.
| req.Header.Set("Content-Type", "application/json") | |
| req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) | |
| req.Header.Set("Content-Type", "application/json") | |
| if apiConfig != nil && apiConfig.ApiKey != nil && *apiConfig.ApiKey != "" { | |
| req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) | |
| } |
🤖 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 138 - 139, The Authorization
header is being set unconditionally using *apiConfig.ApiKey which can be nil for
local Ollama deployments and causes a panic; update the three call sites
(ChatWithMessages, ChatStreamlyWithSender, and ListModels) to only set the
Authorization header when apiConfig.ApiKey is non-nil and non-empty (e.g., check
apiConfig.ApiKey != nil && *apiConfig.ApiKey != ""), mirroring the conditional
guard used in moonshot.go, and leave the Content-Type header unchanged.
| scanner := bufio.NewScanner(resp.Body) | ||
| for scanner.Scan() { | ||
| line := scanner.Text() | ||
| common.Info(line) | ||
|
|
||
| // SSE data line starts with "data:" | ||
| if !strings.HasPrefix(line, "data:") { | ||
| continue | ||
| } | ||
|
|
||
| // Extract JSON after "data:" |
There was a problem hiding this comment.
bufio.Scanner default buffer + logging full lines on the streaming path.
Two concerns on the SSE loop:
bufio.NewScannerhas a defaultMaxScanTokenSizeof 64 KiB. SSEdata:payloads from chat models occasionally exceed this (large tool-call deltas, multi-modal content, base64 images). When that happensscanner.Scan()returnsfalsemid-stream andscanner.Err()reportsbufio.ErrTooLong, truncating the response. Considerscanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)or switching tobufio.Reader.ReadBytes('\n').common.Info(line)logs every raw SSE chunk at info level. Aside from the volume (one log entry per token), the line may contain user prompts/responses — a privacy/PII concern. Lower to debug, or drop entirely.
The same two issues exist in MoonshotModel.ChatStreamlyWithSender (lines 292‑295 of moonshot.go); fixing in one place gives you a cheap precedent for the other.
🤖 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 285 - 295, The SSE loop using
bufio.NewScanner on resp.Body can overflow the default 64KiB token size and is
logging every raw SSE line at info level; update the streaming loop in the
Ollama SSE reader (the scanner usage handling resp.Body) to either set a larger
scanner buffer via scanner.Buffer(make([]byte,0,64*1024), 1024*1024) or replace
the scanner with a bufio.Reader and use ReadBytes('\n') to avoid
bufio.ErrTooLong, and change/remove the common.Info(line) call so raw SSE chunks
are not logged at info level (use common.Debug or drop logging) — apply the same
change pattern to MoonshotModel.ChatStreamlyWithSender where the same
scanner/logging pattern is used.
| func (o OllamaModel) ListModels(apiConfig *APIConfig) ([]string, error) { | ||
| var region = "default" | ||
|
|
||
| if apiConfig.Region != nil { | ||
| region = *apiConfig.Region | ||
| } | ||
|
|
||
| url := fmt.Sprintf("%s/%s", o.BaseURL[region], o.URLSuffix.Models) | ||
|
|
||
| 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)) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to create request: %w", err) | ||
| } | ||
|
|
||
| req.Header.Set("Content-Type", "application/json") | ||
| req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) | ||
|
|
||
| resp, err := o.httpClient.Do(req) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to send request: %w", err) | ||
| } | ||
| defer resp.Body.Close() | ||
|
|
||
| body, err := io.ReadAll(resp.Body) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to read response: %w", err) | ||
| } | ||
|
|
||
| if resp.StatusCode != http.StatusOK { | ||
| return nil, fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body)) | ||
| } | ||
|
|
||
| // Parse response | ||
| var result map[string]interface{} | ||
| if err = json.Unmarshal(body, &result); err != nil { | ||
| return nil, fmt.Errorf("failed to parse response: %w", err) | ||
| } | ||
|
|
||
| // convert result["data"] to []map[string]interface{} | ||
| models := make([]string, 0) | ||
| for _, model := range result["data"].([]interface{}) { | ||
| modelMap := model.(map[string]interface{}) | ||
| modelName := modelMap["id"].(string) | ||
| models = append(models, modelName) | ||
| } | ||
|
|
||
| return models, nil | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🌐 Web query:
Ollama OpenAI-compatible /v1/models response schema fields
💡 Result:
Ollama’s OpenAI-compatible endpoint GET /v1/models returns a top-level JSON object with the same overall “list of models” shape as OpenAI-compatible clients expect, using these fields: 1) Top-level response fields - object: string, set to "list" [1] - data: array of model objects [1] 2) Each item in data (a “model” object) - id: string (the Ollama model name/alias, e.g. mario:latest) [2] - object: string, set to "model" [2] - created: integer (Unix timestamp) corresponding to when the model was last modified [1] - owned_by: string corresponding to the Ollama username, defaulting to "library" [1] Notes / scope - This is for the OpenAI-compatible /v1/models list endpoint. Ollama also documents supported request/response behavior for other OpenAI-compatible endpoints under its OpenAI compatibility documentation. [1] Primary sources: - Ollama OpenAI compatibility docs (section describing /v1/models and the fields it returns) [1] - Ollama PR example payload for GET /v1/models showing the exact JSON keys and example values [2]
Citations:
- 1: https://docs.ollama.com/api/openai-compatibility
- 2: OpenAI: /v1/models and /v1/models/{model} compatibility ollama/ollama#5007
🏁 Script executed:
cat -n internal/entity/models/ollama.go | sed -n '361,415p'Repository: infiniflow/ragflow
Length of output: 1982
Add defensive type assertion checks and remove unnecessary JSON body from GET request.
The code's assumption about Ollama's /v1/models response shape is correct—the endpoint returns objects in a data array with an id field. However, the implementation has two issues:
- The unchecked type assertions at lines 408-410 will panic if the response shape differs (e.g., if a field is missing or has a different type). Use the two-value form (
v, ok := …) and return a descriptive error instead. - Line 377 sends a GET request with an empty JSON body. This is unusual and some proxies may silently drop the body; pass
nilinstead.
Defensive parsing + nil GET body
- req, err := http.NewRequest("GET", url, bytes.NewBuffer(jsonData))
+ req, err := http.NewRequest(http.MethodGet, url, nil)
@@
- models := make([]string, 0)
- for _, model := range result["data"].([]interface{}) {
- modelMap := model.(map[string]interface{})
- modelName := modelMap["id"].(string)
- models = append(models, modelName)
- }
+ rawData, ok := result["data"].([]interface{})
+ if !ok {
+ return nil, fmt.Errorf("unexpected models response shape")
+ }
+ models := make([]string, 0, len(rawData))
+ for _, model := range rawData {
+ modelMap, ok := model.(map[string]interface{})
+ if !ok {
+ continue
+ }
+ if id, ok := modelMap["id"].(string); ok {
+ models = append(models, id)
+ }
+ }🤖 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 361 - 415, In
OllamaModel.ListModels: remove the unnecessary JSON body for the GET (stop
marshalling reqBody and call http.NewRequest("GET", url, nil) instead), and
replace all unchecked assertions when parsing result (result, result["data"],
each model element and modelMap["id"]) with two-value type checks (v, ok := ...)
and return clear errors when types/keys are missing; specifically validate
result is map[string]interface{}, result["data"] is []interface{}, each item is
map[string]interface{}, and the "id" is a string before appending to models to
avoid panics.
| func (o OllamaModel) CheckConnection(apiConfig *APIConfig) error { | ||
| return fmt.Errorf("no such method") | ||
| } |
There was a problem hiding this comment.
CheckConnection always reports failure.
Returning a hard-coded error means Ollama can never pass a connectivity health check, which typically gates provider registration / UI "test connection" flows. Mirror MoonshotModel.CheckConnection and delegate to ListModels.
🛠️ Proposed fix
-func (o OllamaModel) CheckConnection(apiConfig *APIConfig) error {
- return fmt.Errorf("no such method")
-}
+func (o OllamaModel) CheckConnection(apiConfig *APIConfig) error {
+ _, err := o.ListModels(apiConfig)
+ return err
+}📝 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 (o OllamaModel) CheckConnection(apiConfig *APIConfig) error { | |
| return fmt.Errorf("no such method") | |
| } | |
| func (o OllamaModel) CheckConnection(apiConfig *APIConfig) error { | |
| _, err := o.ListModels(apiConfig) | |
| return err | |
| } |
🤖 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 421 - 423,
OllamaModel.CheckConnection currently always returns a hard-coded error,
preventing successful health checks; update OllamaModel.CheckConnection to
mirror MoonshotModel.CheckConnection by calling the provider's ListModels method
(e.g., o.ListModels or the equivalent method used on OllamaModel) and returning
nil if ListModels succeeds or returning the encountered error if it fails, so
the connectivity check reflects the real provider response.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14580 +/- ##
=======================================
Coverage 94.16% 94.16%
=======================================
Files 10 10
Lines 703 703
Branches 112 112
=======================================
Hits 662 662
Misses 25 25
Partials 16 16 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
### What problem does this PR solve? IDK how to implement **`Ollama`** on #14580 but it's totally wrong. This is the rewrite version for **`Ollama`** **Verified from CLI** ``` # Embed RAGFlow(user)> embed text 'what is rag' 'who are you' with 'nomic-embed-text:latest@test12@ollama' dimension 1024; +-----------+-------+ | dimension | index | +-----------+-------+ | 768 | 0 | | 768 | 1 | +-----------+-------+ # Chat RAGFlow(user)> think chat with 'qwen3:0.6b@test12@ollama' message 'who r u' Thinking: Okay, the user asked, "Who r u?" I need to respond appropriately. First, I should acknowledge their question. Since I'm an AI, I don't have a physical form, but I can confirm that I'm a large language model. I should keep the response friendly and offer help. Let me make sure I'm not making up any information and that the response is natural. Also, I should check for any typos and ensure clarity. Alright, that should cover it. Answer: I'm an AI language model, and I don't have a physical form. However, I can tell you that I'm designed to assist with questions and tasks. How can I help you today? Time: 2.914285 RAGFlow(user)> stream think chat with 'qwen3:0.6b@test12@ollama' message 'who r u' Thinking: , the user asked, "Who are you?" I need to respond appropriately. Since I'm an AI assistant, I should mention that I don't have a physical form or a mind. I should also clarify that I can help with various tasks like answering questions or providing information. It's important to keep the response friendly and informative while maintaining the correct tone. Answer: don't have a physical form or a mind, but I'm here to help with your questions or tasks! What can I do for you today? Time: 1.740047 # LisyModels RAGFlow(user)> list supported models from 'ollama' 'test12' +-------------------------+ | model_name | +-------------------------+ | nomic-embed-text:latest | | qwen3:0.6b | +-------------------------+ ``` ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue) - [x] Refactoring
What problem does this PR solve?
implement
OllamaproviderType of change