Repository navigation
Go: implement provider: Vllm - #14532
Conversation
📝 WalkthroughWalkthroughThis PR implements streaming chat and model listing capabilities for the vLLM provider by adding Changes
Sequence DiagramsequenceDiagram
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 inconclusive)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Review rate limit: 7/8 reviews remaining, refill in 7 minutes and 30 seconds.Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (2)
internal/entity/models/vllm.gointernal/service/model_service.go
| 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() |
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
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.
| 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.
| // For local deployed models | ||
| if baseURL, ok := extra["base_url"]; ok && baseURL != "" { | ||
| newURL := map[string]string{ | ||
| region: baseURL, | ||
| } | ||
| providerInfo.ModelDriver = providerInfo.ModelDriver.NewInstance(newURL) | ||
| } |
There was a problem hiding this comment.
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.
| newURL := map[string]string{ | ||
| region: extra["base_url"], | ||
| } | ||
| newProviderInfo := providerInfo.ModelDriver.NewInstance(newURL) | ||
|
|
||
| err = newProviderInfo.ChatStreamlyWithSender(&modelName, &message, apiConfig, modelConfig, sender) |
There was a problem hiding this comment.
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.
| 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 Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
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]>
### 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
### 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
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:
Added Standard vLLM Provider (
vllm.go,vllm.json):VllmModeldriver strictly adhering to the OpenAI API specification.AsyncChatfor Qwen/GLM prefixes), ensuring standard/v1/chat/completionscompatibility.ListModelsto use safe JSON parsing (resolving nil pointer panics) and standardGETrequests without bodies.APIConfig.Regionfallback logic to prevent emptybase_urlfetching when checking models.Fixed
ChatToModelStreamWithSenderBug (model_service.go):model is disablederror when streaming chat with local database-saved models.if modelInfo.Status == "active"block to correctly invokeNewInstanceand inject the dynamicbase_urlinto the provider driver before starting the SSE stream.Fixed
ListSupportedModelsBug (model_service.go):NewInstanceinjection forbase_url. Previously, the list models function used the static JSON config without injecting user-configured dynamic URLs from the database, resulting in anunsupported protocol scheme ""error.Type of change