Skip to content

Go: implement provider: Ollama - #14580

Merged
JinHai-CN merged 3 commits into
infiniflow:mainfrom
Haruko386:main
May 6, 2026
Merged

JinHai-CN merged 3 commits into
infiniflow:mainfrom
Haruko386:main

Conversation

@Haruko386

Copy link
Copy Markdown
Member

What problem does this PR solve?

implement Ollama provider

Type of change

  • New Feature (non-breaking change which adds functionality)
  • Refactoring

@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label May 6, 2026
@coderabbitai

coderabbitai Bot commented May 6, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This 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.

Changes

Ollama Model Provider Integration

Layer / File(s) Summary
Configuration
conf/models/ollama.json
New Ollama model configuration with URL mappings for chat and models endpoints, marked as "local" class.
Data Structures & Initialization
internal/entity/models/ollama.go (lines 16–89)
OllamaModel type defined with BaseURL, URLSuffix, and httpClient fields; NewOllamaModel constructor initializes HTTP client with configured timeout and transport; NewInstance preserves URL suffix and client settings across instances.
Core Chat Operations
internal/entity/models/ollama.go (lines 99–313)
ChatWithMessages resolves region, selects endpoint based on model type prefix, converts messages to Ollama API format, applies config overrides (temperature, max_tokens, top_p, stop, thinking), performs POST request, parses response, and extracts content with thinking/reasoning.
Streaming Chat
internal/entity/models/ollama.go (lines 316–548)
ChatStreamlyWithSender enables Server-Sent Events (SSE) streaming with region resolution, endpoint selection, request body streaming mode, line-by-line SSE parsing, incremental delta content delivery via callback, and final [DONE] marker emission.
Model Discovery & Stubs
internal/entity/models/ollama.go (lines 551–655)
ListModels queries and parses available models from Ollama; Name returns "ollama"; placeholder stubs for Encode, Rerank, Balance, and CheckConnection return not-implemented errors.

Model Configuration & Interface Refinements

Layer / File(s) Summary
Temperature Tuning
internal/entity/models/moonshot.go
Moonshot model default temperature lowered from 1 to 0.6 in ChatWithMessages request body.
Interface Cleanup
internal/entity/models/vllm.go
Removed deprecated Chat method from VllmModel; ChatWithMessages, streaming, and other methods remain unchanged.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested labels

size:L

Poem

🐰 A new Ollama hops into the fold,
Chat and streaming, both swift and bold!
Moonshot's temperature cooled just right,
VllmChat removed—interfaces tight!
Local models now dance in the night. 🌙

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Go: implement provider: Ollama' clearly and specifically describes the main change - adding an Ollama provider implementation in Go.
Description check ✅ Passed The PR description includes both required template sections: 'What problem does this PR solve?' and 'Type of change' with appropriate selections, though the problem statement is minimal.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@Haruko386 Haruko386 added the ci Continue Integration label May 6, 2026
@Haruko386
Haruko386 marked this pull request as draft May 6, 2026 02:58
@Haruko386
Haruko386 marked this pull request as ready for review May 6, 2026 02:58

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 7

🧹 Nitpick comments (2)
internal/entity/models/ollama.go (2)

88-92: 💤 Low value

Hard-coded default temperature: 1 is 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 with 1 and is overwritten only when chatModelConfig != nil && chatModelConfig.Temperature != nil. If the rationale for the Moonshot change applies here too, consider matching it; otherwise document why Ollama keeps 1.

🤖 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 value

Receiver type inconsistency.

Constructor NewOllamaModel returns *OllamaModel, but every method (NewInstance, Name, ChatWithMessages, ChatStreamlyWithSender, …) is declared on the value receiver o OllamaModel. This deviates from MoonshotModel (pointer receivers) and means each call copies the struct including the *http.Client pointer. While interface satisfaction still works because NewOllamaModel returns 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 to OllamaModel).

♻️ 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

📥 Commits

Reviewing files that changed from the base of the PR and between aa57b5b and e46ec9e.

📒 Files selected for processing (4)
  • conf/models/ollama.json
  • internal/entity/models/moonshot.go
  • internal/entity/models/ollama.go
  • internal/entity/models/vllm.go
💤 Files with no reviewable changes (1)
  • internal/entity/models/vllm.go

Comment thread conf/models/ollama.json
Comment on lines +3 to +6
"url_suffix": {
"chat": "chat/completions",
"models": "models"
},

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

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.

Comment on lines +64 to +75
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)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Two correctness bugs in endpoint selection.

  1. 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), so ChatWithMessages will never take the AsyncChat branch while ChatStreamlyWithSender will. Pick one separator and apply it consistently.
  2. o.URLSuffix.AsyncChat is empty for Ollama. The companion conf/models/ollama.json only defines chat and models, so the AsyncChat branch produces a URL like <baseURL>/ and the request 404s. Either define async_chat in the config or remove this branch entirely (Ollama's OpenAI-compatible surface has no async equivalent).
  3. apiConfig.Region is dereferenced without checking apiConfig itself for nil (MoonshotModel.ChatWithMessages does apiConfig != nil && apiConfig.Region != nil). If a caller ever passes nil, 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.

Suggested change
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.

Comment on lines +94 to +190
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
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

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).

Comment on lines +138 to +139
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

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.

Suggested change
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.

Comment on lines +285 to +295
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:"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

bufio.Scanner default buffer + logging full lines on the streaming path.

Two concerns on the SSE loop:

  1. bufio.NewScanner has a default MaxScanTokenSize of 64 KiB. SSE data: payloads from chat models occasionally exceed this (large tool-call deltas, multi-modal content, base64 images). When that happens scanner.Scan() returns false mid-stream and scanner.Err() reports bufio.ErrTooLong, truncating the response. Consider scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024) or switching to bufio.Reader.ReadBytes('\n').
  2. 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.

Comment on lines +361 to +415
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
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 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:


🏁 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 nil instead.
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.

Comment on lines +421 to +423
func (o OllamaModel) CheckConnection(apiConfig *APIConfig) error {
return fmt.Errorf("no such method")
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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.

Suggested change
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

codecov Bot commented May 6, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (7335916) to head (dd96c33).

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@JinHai-CN
JinHai-CN merged commit cd54c08 into infiniflow:main May 6, 2026
1 check passed
JinHai-CN pushed a commit that referenced this pull request May 25, 2026
### 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants