Skip to content

Go: implement provider: Vllm - #14532

Merged
JinHai-CN merged 1 commit into
infiniflow:mainfrom
Haruko386:main
Apr 30, 2026
Merged

JinHai-CN merged 1 commit into
infiniflow:mainfrom
Haruko386:main

Conversation

@Haruko386

Copy link
Copy Markdown
Member

What problem does this PR solve?

Implement the vLLM model provider for RAGFlow to fully support local and self-hosted open-source models (e.g., Qwen, GLM, Llama) via the vLLM framework, and fix several critical bugs related to model instance management and API requests.

Key changes and fixes:

  1. Added Standard vLLM Provider (vllm.go, vllm.json):

    • Implemented VllmModel driver strictly adhering to the OpenAI API specification.
    • Removed hardcoded and dangerous routing logic (e.g., forcing AsyncChat for Qwen/GLM prefixes), ensuring standard /v1/chat/completions compatibility.
    • Refactored ListModels to use safe JSON parsing (resolving nil pointer panics) and standard GET requests without bodies.
    • Added APIConfig.Region fallback logic to prevent empty base_url fetching when checking models.
  2. Fixed ChatToModelStreamWithSender Bug (model_service.go):

    • Resolved the model is disabled error when streaming chat with local database-saved models.
    • Added the missing if modelInfo.Status == "active" block to correctly invoke NewInstance and inject the dynamic base_url into the provider driver before starting the SSE stream.
  3. Fixed ListSupportedModels Bug (model_service.go):

    • Added dynamic NewInstance injection for base_url. Previously, the list models function used the static JSON config without injecting user-configured dynamic URLs from the database, resulting in an unsupported protocol scheme "" error.

Type of change

  • Bug Fix (non-breaking change which fixes an issue)
  • New Feature (non-breaking change which adds functionality)
  • Documentation Update
  • Refactoring
  • Performance Improvement
  • Other (please describe):

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Apr 30, 2026
@coderabbitai

coderabbitai Bot commented Apr 30, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This PR implements streaming chat and model listing capabilities for the vLLM provider by adding ChatStreamlyWithSender (which processes Server-Sent Event streams and forwards content chunks to a callback) and ListModels (which fetches and parses available models). The service layer is updated to detect local deployments and use region-scoped driver instances for active models.

Changes

Cohort / File(s) Summary
vLLM Provider Implementation
internal/entity/models/vllm.go
Implements ChatStreamlyWithSender to handle streaming requests with SSE event parsing, extracting content and reasoning_content from chunks, and forwarding non-empty results to callback; implements ListModels to fetch and parse model listings from region-scoped endpoints; adds buffering and logging imports.
Model Service Layer
internal/service/model_service.go
Updates ListSupportedModels to detect local deployments via extra["base_url"] and swap to region-scoped driver instances; enhances ChatToModelStreamWithSender to capture model info, branch on active status, rebuild API config with region-specific values, and route streaming through the new ChatStreamlyWithSender implementation.

Sequence Diagram

sequenceDiagram
    participant Client
    participant Service
    participant Provider as vLLM Provider
    participant API as External API
    
    Client->>Service: Request streaming chat
    Service->>Service: Detect local deployment (check extra["base_url"])
    Service->>Service: Create region-scoped driver instance
    Service->>Provider: ChatStreamlyWithSender (with region/model config)
    Provider->>Provider: Compute target endpoint per region & model type
    Provider->>Provider: Build streaming request with tuning fields
    Provider->>API: Send request with Bearer auth
    API-->>Provider: SSE stream (data: events)
    Provider->>Provider: Parse SSE events incrementally
    Provider->>Provider: Extract content & reasoning_content from choices[0].delta
    Provider->>Service: Send chunk via callback
    Service-->>Client: Forward content chunk
    API-->>Provider: [DONE] or finish_reason
    Provider->>Service: Send [DONE] terminator via callback
    Service-->>Client: Stream complete
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested labels

ci, size:L

Poem

🐰 A vLLM stream now flows so fine,
With SSE events aligned in line,
Each chunk of thought and reasoning gleams,
As rabbit routers fulfil streaming dreams! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Title check ❓ Inconclusive The title 'Go: implement provider: Vllm' is partially related to the changeset but is vague and overly broad, failing to highlight the main fixes and oversimplifying the scope. Consider a more specific title like 'Add vLLM provider and fix model instance management bugs' to better reflect both the new feature and critical bug fixes.
✅ Passed checks (4 passed)
Check name Status Explanation
Description check ✅ Passed The PR description fully addresses the template by explaining the problem, listing key changes in detail, and correctly marking both bug fix and new feature checkboxes.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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
Review rate limit: 7/8 reviews remaining, refill in 7 minutes and 30 seconds.

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

@Haruko386 Haruko386 added the ci Continue Integration label Apr 30, 2026
@Haruko386
Haruko386 marked this pull request as draft April 30, 2026 07:37
@Haruko386
Haruko386 marked this pull request as ready for review April 30, 2026 07:37

@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: 5

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@internal/entity/models/vllm.go`:
- Line 422: Remove the raw SSE line log by deleting the logger.Info(line) call
in internal/entity/models/vllm.go; instead, if you need observability, log
non-sensitive metadata at a lower level (e.g., use logger.Debugf or
logger.Trace) and avoid including the full "line" content — for example log
event type, tenant-safe identifiers or length only, or a redacted summary — so
replace logger.Info(line) with a debug/log statement that does not print the raw
SSE payload.
- Around line 419-484: The loop currently always emits the OpenAI "[DONE]"
marker even when bufio.NewScanner() later reports an error (e.g., token too
long), which masks truncated streams; change the post-loop logic to check
scanner.Err() and if it is non-nil return that error immediately (without
calling sender with "[DONE]"), and only send the endOfStream "[DONE]" via sender
when scanner.Err() == nil; reference the bufio.NewScanner usage, the scanning
loop that calls sender, and the endOfStream variable to locate where to gate the
"[DONE]" emission.
- Around line 501-541: The request currently marshals an empty JSON body and
sends it with http.NewRequest("GET", url, bytes.NewBuffer(jsonData)) and then
blindly type-asserts result["data"] and nested fields, which can panic; change
the request to a bodyless GET by passing nil as the body (remove json.Marshal
and bytes.NewBuffer usage), and add defensive checks when parsing the response
in the code that handles result: verify result["data"] exists and is a
[]interface{}, for each entry ensure it is a map[string]interface{} before
accessing "id", verify that "id" is a string, and append safely to the models
slice (return a clear error if the response shape is unexpected). Ensure
references to the existing variables/functions (req creation, http.NewRequest,
result map handling, and the loop that builds models) are updated accordingly.

In `@internal/service/model_service.go`:
- Around line 891-896: Only set/override the provider URL when
instance.Extra["base_url"] is non-empty: check that extra :=
instance.Extra["base_url"] != "" before constructing newURL and calling
providerInfo.ModelDriver.NewInstance(newURL); otherwise call
providerInfo.ModelDriver.NewInstance(nil) (or the variant that leaves defaults)
so you don't replace the provider endpoint with an empty string, and then call
newProviderInfo.ChatStreamlyWithSender(&modelName, &message, apiConfig,
modelConfig, sender) as before.
- Around line 202-208: The code currently mutates the global provider by
assigning providerInfo.ModelDriver =
providerInfo.ModelDriver.NewInstance(newURL) when extra["base_url"] is set,
allowing one request to overwrite the driver for others; instead create a
request-scoped driver instance (e.g., newDriver :=
providerInfo.ModelDriver.NewInstance(newURL)) and use that local variable for
this request’s operations without reassigning providerInfo.ModelDriver so the
global provider stays unchanged; locate the logic around
providerInfo.ModelDriver.NewInstance, extra["base_url"], and region and replace
the assignment with a local driver variable passed into the remaining request
flow.
🪄 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: 9df5e49d-e9f6-4d10-bdc0-087aa29b9312

📥 Commits

Reviewing files that changed from the base of the PR and between 265f92c and 2fed66f.

📒 Files selected for processing (2)
  • internal/entity/models/vllm.go
  • internal/service/model_service.go

Comment on lines +419 to +484
scanner := bufio.NewScanner(resp.Body)
for scanner.Scan() {
line := scanner.Text()
logger.Info(line)

// SSE data line starts with "data:"
if !strings.HasPrefix(line, "data:") {
continue
}

// Extract JSON after "data:"
data := strings.TrimSpace(line[5:])

// [DONE] marks the end of stream
if data == "[DONE]" {
break
}

// Parse the JSON event
var event map[string]interface{}
if err = json.Unmarshal([]byte(data), &event); err != nil {
continue
}

choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
continue
}

firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
continue
}

delta, ok := firstChoice["delta"].(map[string]interface{})
if !ok {
continue
}

reasoningContent, ok := delta["reasoning_content"].(string)
if ok && reasoningContent != "" {
if err := sender(nil, &reasoningContent); err != nil {
return err
}
}

content, ok := delta["content"].(string)
if ok && content != "" {
if err := sender(&content, nil); err != nil {
return err
}
}

finishReason, ok := firstChoice["finish_reason"].(string)
if ok && finishReason != "" {
break
}
}

// Send [DONE] marker for OpenAI compatibility
endOfStream := "[DONE]"
if err = sender(&endOfStream, nil); err != nil {
return err
}

return scanner.Err()

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

Treat scanner failures as stream errors, not clean completion.

bufio.Scanner caps tokens at 64 KiB by default, which long SSE chunks can exceed. In that case scanner.Err() becomes non-nil, but this code still emits [DONE], so clients can see a successful end marker for a truncated stream.

Suggested fix
 	scanner := bufio.NewScanner(resp.Body)
+	scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)
 	for scanner.Scan() {
 		line := scanner.Text()
-		logger.Info(line)
 
 		// SSE data line starts with "data:"
 		if !strings.HasPrefix(line, "data:") {
 			continue
@@
-	// Send [DONE] marker for OpenAI compatibility
-	endOfStream := "[DONE]"
-	if err = sender(&endOfStream, nil); err != nil {
-		return err
+	if err := scanner.Err(); err != nil {
+		return err
 	}
 
-	return scanner.Err()
+	endOfStream := "[DONE]"
+	return sender(&endOfStream, nil)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
scanner := bufio.NewScanner(resp.Body)
for scanner.Scan() {
line := scanner.Text()
logger.Info(line)
// SSE data line starts with "data:"
if !strings.HasPrefix(line, "data:") {
continue
}
// Extract JSON after "data:"
data := strings.TrimSpace(line[5:])
// [DONE] marks the end of stream
if data == "[DONE]" {
break
}
// Parse the JSON event
var event map[string]interface{}
if err = json.Unmarshal([]byte(data), &event); err != nil {
continue
}
choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
continue
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
continue
}
delta, ok := firstChoice["delta"].(map[string]interface{})
if !ok {
continue
}
reasoningContent, ok := delta["reasoning_content"].(string)
if ok && reasoningContent != "" {
if err := sender(nil, &reasoningContent); err != nil {
return err
}
}
content, ok := delta["content"].(string)
if ok && content != "" {
if err := sender(&content, nil); err != nil {
return err
}
}
finishReason, ok := firstChoice["finish_reason"].(string)
if ok && finishReason != "" {
break
}
}
// Send [DONE] marker for OpenAI compatibility
endOfStream := "[DONE]"
if err = sender(&endOfStream, nil); err != nil {
return err
}
return scanner.Err()
scanner := bufio.NewScanner(resp.Body)
scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)
for scanner.Scan() {
line := scanner.Text()
// SSE data line starts with "data:"
if !strings.HasPrefix(line, "data:") {
continue
}
// Extract JSON after "data:"
data := strings.TrimSpace(line[5:])
// [DONE] marks the end of stream
if data == "[DONE]" {
break
}
// Parse the JSON event
var event map[string]interface{}
if err = json.Unmarshal([]byte(data), &event); err != nil {
continue
}
choices, ok := event["choices"].([]interface{})
if !ok || len(choices) == 0 {
continue
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
continue
}
delta, ok := firstChoice["delta"].(map[string]interface{})
if !ok {
continue
}
reasoningContent, ok := delta["reasoning_content"].(string)
if ok && reasoningContent != "" {
if err := sender(nil, &reasoningContent); err != nil {
return err
}
}
content, ok := delta["content"].(string)
if ok && content != "" {
if err := sender(&content, nil); err != nil {
return err
}
}
finishReason, ok := firstChoice["finish_reason"].(string)
if ok && finishReason != "" {
break
}
}
if err := scanner.Err(); err != nil {
return err
}
endOfStream := "[DONE]"
return sender(&endOfStream, nil)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/entity/models/vllm.go` around lines 419 - 484, The loop currently
always emits the OpenAI "[DONE]" marker even when bufio.NewScanner() later
reports an error (e.g., token too long), which masks truncated streams; change
the post-loop logic to check scanner.Err() and if it is non-nil return that
error immediately (without calling sender with "[DONE]"), and only send the
endOfStream "[DONE]" via sender when scanner.Err() == nil; reference the
bufio.NewScanner usage, the scanning loop that calls sender, and the endOfStream
variable to locate where to gate the "[DONE]" emission.

scanner := bufio.NewScanner(resp.Body)
for scanner.Scan() {
line := scanner.Text()
logger.Info(line)

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

Remove the raw SSE line log.

Each line can contain tenant prompts, model output, or reasoning_content, so logging it at info level leaks sensitive data and will also flood production logs during long streams.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/entity/models/vllm.go` at line 422, Remove the raw SSE line log by
deleting the logger.Info(line) call in internal/entity/models/vllm.go; instead,
if you need observability, log non-sensitive metadata at a lower level (e.g.,
use logger.Debugf or logger.Trace) and avoid including the full "line" content —
for example log event type, tenant-safe identifiers or length only, or a
redacted summary — so replace logger.Info(line) with a debug/log statement that
does not print the raw SSE payload.

Comment on lines +501 to +541
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 := z.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)

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

Use a bodyless GET and validate the response shape before casting.

Sending a JSON body with GET hurts compatibility with proxies/load balancers, and the unchecked assertions on result["data"], each model entry, and "id" will panic on any non-standard or error payload from the upstream API.

Suggested fix
-	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(http.MethodGet, url, nil)
 	if err != nil {
 		return nil, fmt.Errorf("failed to create request: %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)
+	rawModels, ok := result["data"].([]interface{})
+	if !ok {
+		return nil, fmt.Errorf("invalid models response: missing data array")
+	}
+
+	models := make([]string, 0, len(rawModels))
+	for _, rawModel := range rawModels {
+		modelMap, ok := rawModel.(map[string]interface{})
+		if !ok {
+			return nil, fmt.Errorf("invalid model entry format")
+		}
+		modelName, ok := modelMap["id"].(string)
+		if !ok || modelName == "" {
+			return nil, fmt.Errorf("invalid model id in response")
+		}
+		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.

Suggested change
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 := z.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)
req, err := http.NewRequest(http.MethodGet, url, nil)
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 := z.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)
}
rawModels, ok := result["data"].([]interface{})
if !ok {
return nil, fmt.Errorf("invalid models response: missing data array")
}
models := make([]string, 0, len(rawModels))
for _, rawModel := range rawModels {
modelMap, ok := rawModel.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("invalid model entry format")
}
modelName, ok := modelMap["id"].(string)
if !ok || modelName == "" {
return nil, fmt.Errorf("invalid model id in response")
}
models = append(models, modelName)
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/entity/models/vllm.go` around lines 501 - 541, The request currently
marshals an empty JSON body and sends it with http.NewRequest("GET", url,
bytes.NewBuffer(jsonData)) and then blindly type-asserts result["data"] and
nested fields, which can panic; change the request to a bodyless GET by passing
nil as the body (remove json.Marshal and bytes.NewBuffer usage), and add
defensive checks when parsing the response in the code that handles result:
verify result["data"] exists and is a []interface{}, for each entry ensure it is
a map[string]interface{} before accessing "id", verify that "id" is a string,
and append safely to the models slice (return a clear error if the response
shape is unexpected). Ensure references to the existing variables/functions (req
creation, http.NewRequest, result map handling, and the loop that builds models)
are updated accordingly.

Comment on lines +202 to +208
// For local deployed models
if baseURL, ok := extra["base_url"]; ok && baseURL != "" {
newURL := map[string]string{
region: baseURL,
}
providerInfo.ModelDriver = providerInfo.ModelDriver.NewInstance(newURL)
}

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

Keep the driver instance request-scoped here.

Assigning providerInfo.ModelDriver = ...NewInstance(...) stores a tenant-specific base_url back onto the provider object returned by the global manager. That lets one request overwrite the driver used by later requests for the same provider.

Suggested fix
-	// For local deployed models
-	if baseURL, ok := extra["base_url"]; ok && baseURL != "" {
-		newURL := map[string]string{
-			region: baseURL,
-		}
-		providerInfo.ModelDriver = providerInfo.ModelDriver.NewInstance(newURL)
-	}
-
-	return providerInfo.ModelDriver.ListModels(apiConfig)
+	driver := providerInfo.ModelDriver
+	if baseURL, ok := extra["base_url"]; ok && baseURL != "" {
+		driver = driver.NewInstance(map[string]string{
+			region: baseURL,
+		})
+	}
+
+	return driver.ListModels(apiConfig)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/service/model_service.go` around lines 202 - 208, The code currently
mutates the global provider by assigning providerInfo.ModelDriver =
providerInfo.ModelDriver.NewInstance(newURL) when extra["base_url"] is set,
allowing one request to overwrite the driver for others; instead create a
request-scoped driver instance (e.g., newDriver :=
providerInfo.ModelDriver.NewInstance(newURL)) and use that local variable for
this request’s operations without reassigning providerInfo.ModelDriver so the
global provider stays unchanged; locate the logic around
providerInfo.ModelDriver.NewInstance, extra["base_url"], and region and replace
the assignment with a local driver variable passed into the remaining request
flow.

Comment on lines +891 to +896
newURL := map[string]string{
region: extra["base_url"],
}
newProviderInfo := providerInfo.ModelDriver.NewInstance(newURL)

err = newProviderInfo.ChatStreamlyWithSender(&modelName, &message, apiConfig, modelConfig, sender)

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

Only override the provider URL when base_url is actually set.

This branch now runs for any active model. If instance.Extra["base_url"] is empty, NewInstance replaces the provider’s normal endpoint with "", which brings back the unsupported protocol scheme "" failure for non-local instances.

Suggested fix
-		newURL := map[string]string{
-			region: extra["base_url"],
-		}
-		newProviderInfo := providerInfo.ModelDriver.NewInstance(newURL)
+		driver := providerInfo.ModelDriver
+		if baseURL := extra["base_url"]; baseURL != "" {
+			driver = driver.NewInstance(map[string]string{
+				region: baseURL,
+			})
+		}
 
-		err = newProviderInfo.ChatStreamlyWithSender(&modelName, &message, apiConfig, modelConfig, sender)
+		err = driver.ChatStreamlyWithSender(&modelName, &message, apiConfig, modelConfig, sender)
📝 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
newURL := map[string]string{
region: extra["base_url"],
}
newProviderInfo := providerInfo.ModelDriver.NewInstance(newURL)
err = newProviderInfo.ChatStreamlyWithSender(&modelName, &message, apiConfig, modelConfig, sender)
driver := providerInfo.ModelDriver
if baseURL := extra["base_url"]; baseURL != "" {
driver = driver.NewInstance(map[string]string{
region: baseURL,
})
}
err = driver.ChatStreamlyWithSender(&modelName, &message, apiConfig, modelConfig, sender)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/service/model_service.go` around lines 891 - 896, Only set/override
the provider URL when instance.Extra["base_url"] is non-empty: check that extra
:= instance.Extra["base_url"] != "" before constructing newURL and calling
providerInfo.ModelDriver.NewInstance(newURL); otherwise call
providerInfo.ModelDriver.NewInstance(nil) (or the variant that leaves defaults)
so you don't replace the provider endpoint with an empty string, and then call
newProviderInfo.ChatStreamlyWithSender(&modelName, &message, apiConfig,
modelConfig, sender) as before.

@codecov

codecov Bot commented Apr 30, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (265f92c) to head (2fed66f).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14532   +/-   ##
=======================================
  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 93f3b90 into infiniflow:main Apr 30, 2026
1 check passed
@davidv399 davidv399 mentioned this pull request Apr 30, 2026
1 task done
@coderabbitai coderabbitai Bot mentioned this pull request May 6, 2026
2 tasks done
JinHai-CN added a commit that referenced this pull request May 6, 2026
Closes #14552 

### What problem does this PR solve?

Add a Go driver for xAI (Grok models).

The config file conf/models/xai.json has been in the repo since the
early Go provider work, but internal/entity/models/factory.go had no
case for "xai". So any xAI request fell through to the dummy driver
and never reached the API. This PR adds the missing driver and wires it
up.

### What this PR includes

- New file internal/entity/models/xai.go with an XAIModel that
implements the ModelDriver interface.
- factory.go: route the "xai" provider name to NewXAIModel.

### How the driver works

- xAI exposes an OpenAI-compatible API at https://api.x.ai/v1.
- ChatWithMessages and ChatStreamlyWithSender post to /chat/completions
in the same shape the moonshot and deepseek drivers use.
- ListModels and CheckConnection call /models to confirm the API key
works and to list available model ids.
- reasoning_content is passed through for grok-3-mini and other xAI
reasoning models, both in the non-stream and stream paths.
- Encode, Rerank, and Balance are not part of the public xAI API at the
moment, so they return a clear "not implemented" or "no such method"
error.

### Type of change

- [x] New Feature (non-breaking change which adds functionality)

### How was this tested?

- go build ./internal/entity/models/... in a clean go 1.25 image (the
  go.mod minimum) returns exit 0 with no errors.
- Method set of XAIModel matches the ModelDriver interface: NewInstance,
  Name, ChatWithMessages, ChatStreamlyWithSender, Encode, Rerank,
  ListModels, Balance, CheckConnection.
- Pattern parity with the merged moonshot (#14433), volcengine (#14460),
  minimax (#14478), and vllm (#14532) PRs.

---------

Co-authored-by: Jin Hai <[email protected]>
@coderabbitai coderabbitai Bot mentioned this pull request May 6, 2026
1 task done
@pandadev66 pandadev66 mentioned this pull request May 7, 2026
1 task done
JinHai-CN pushed a commit that referenced this pull request May 7, 2026
### What problem does this PR solve?

Add a Go driver for OpenAI (GPT models).

The config file conf/models/openai.json has been in the repo for a while
with the full GPT-5 model list, but
internal/entity/models/factory.go had no case for "openai". So any
tenant that configured OpenAI as a model provider in the Go layer fell
through to the default branch and got the dummy driver. Chat, list
models, and check connection all returned dummy responses instead of
reaching the API.

OpenAI is the most commonly requested provider and the JSON config
already ships with the repo, so this gap is high impact even though the
JSON has been there for some time.

### What this PR includes

- New file internal/entity/models/openai.go with an OpenAIModel that
implements the ModelDriver interface.
- factory.go: route the "openai" provider name to NewOpenAIModel.
- conf/models/openai.json: add "models": "models" under url_suffix so
ListModels can hit /v1/models with no hardcoded fallback.

### How the driver works

- OpenAI exposes the canonical OpenAI-compatible API at
https://api.openai.com/v1.
- ChatWithMessages and ChatStreamlyWithSender post to /chat/completions
in the same shape the moonshot, vllm, and xai drivers use.
- ListModels and CheckConnection call /models to list available ids and
confirm the API key works.
- reasoning_content is passed through for the o-series and other
reasoning models, in both the non-stream and stream paths.
- Encode (embeddings) is left as "not implemented" for now, the same way
the other recent provider drivers do it. Rerank and Balance are not part
of OpenAI's public API surface in this layer and return a clear "not
implemented" or "no such method" error.

### Type of change

- [x] New Feature (non-breaking change which adds functionality)

### How was this tested?

- go build ./internal/entity/models/... in a clean go 1.25 image (the
go.mod minimum) returns exit 0 with no errors.
- Method set of OpenAIModel matches the ModelDriver interface:
NewInstance, Name, ChatWithMessages, ChatStreamlyWithSender, Encode,
Rerank, ListModels, Balance, CheckConnection.
- Pattern parity with the merged moonshot (#14433), volcengine (#14460),
minimax (#14478), vllm (#14532), xai (#14550), and lm-studio (#14586)
PRs.

Closes #14604
@coderabbitai coderabbitai Bot mentioned this pull request May 9, 2026
8 of 9 tasks
@tmimmanuel tmimmanuel mentioned this pull request May 12, 2026
1 task done
@coderabbitai coderabbitai Bot mentioned this pull request May 12, 2026
1 task done
@coderabbitai coderabbitai Bot mentioned this pull request May 20, 2026
6 tasks done
Ricardo-M-L pushed a commit to Ricardo-M-L/ragflow that referenced this pull request Aug 17, 2026
### What problem does this PR solve?

Add a Go driver for OpenAI (GPT models).

The config file conf/models/openai.json has been in the repo for a while
with the full GPT-5 model list, but
internal/entity/models/factory.go had no case for "openai". So any
tenant that configured OpenAI as a model provider in the Go layer fell
through to the default branch and got the dummy driver. Chat, list
models, and check connection all returned dummy responses instead of
reaching the API.

OpenAI is the most commonly requested provider and the JSON config
already ships with the repo, so this gap is high impact even though the
JSON has been there for some time.

### What this PR includes

- New file internal/entity/models/openai.go with an OpenAIModel that
implements the ModelDriver interface.
- factory.go: route the "openai" provider name to NewOpenAIModel.
- conf/models/openai.json: add "models": "models" under url_suffix so
ListModels can hit /v1/models with no hardcoded fallback.

### How the driver works

- OpenAI exposes the canonical OpenAI-compatible API at
https://api.openai.com/v1.
- ChatWithMessages and ChatStreamlyWithSender post to /chat/completions
in the same shape the moonshot, vllm, and xai drivers use.
- ListModels and CheckConnection call /models to list available ids and
confirm the API key works.
- reasoning_content is passed through for the o-series and other
reasoning models, in both the non-stream and stream paths.
- Encode (embeddings) is left as "not implemented" for now, the same way
the other recent provider drivers do it. Rerank and Balance are not part
of OpenAI's public API surface in this layer and return a clear "not
implemented" or "no such method" error.

### Type of change

- [x] New Feature (non-breaking change which adds functionality)

### How was this tested?

- go build ./internal/entity/models/... in a clean go 1.25 image (the
go.mod minimum) returns exit 0 with no errors.
- Method set of OpenAIModel matches the ModelDriver interface:
NewInstance, Name, ChatWithMessages, ChatStreamlyWithSender, Encode,
Rerank, ListModels, Balance, CheckConnection.
- Pattern parity with the merged moonshot (infiniflow#14433), volcengine (infiniflow#14460),
minimax (infiniflow#14478), vllm (infiniflow#14532), xai (infiniflow#14550), and lm-studio (infiniflow#14586)
PRs.

Closes infiniflow#14604
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants