Repository navigation
Go: implement provider: Nvidia - #14623
Conversation
📝 WalkthroughWalkthroughThis PR adds Nvidia as a supported AI model provider to the RAGFlow system. It includes configuration for Nvidia models, implements the NvidiaModel driver with both streaming and non-streaming chat endpoints, registers the provider in the factory dispatch, and improves error handling for connection and timeout failures. ChangesNvidia Model Provider Integration
Sequence DiagramsequenceDiagram
participant Client
participant NvidiaModel
participant NvidiaAPI
participant Sender
alt Non-Streaming Chat
Client->>NvidiaModel: ChatWithMessages(messages)
NvidiaModel->>NvidiaModel: Select region-based URL
NvidiaModel->>NvidiaModel: Build POST request payload
NvidiaModel->>NvidiaAPI: POST with Authorization header
NvidiaAPI-->>NvidiaModel: JSON response
NvidiaModel->>NvidiaModel: Parse choices[0].message.content
NvidiaModel->>NvidiaModel: GetThinkingAndAnswer(content)
NvidiaModel-->>Client: ChatResponse
else Streaming Chat
Client->>NvidiaModel: ChatStreamlyWithSender(messages, sender)
NvidiaModel->>NvidiaModel: Build POST request with stream:true
NvidiaModel->>NvidiaAPI: POST with Authorization header
NvidiaAPI-->>NvidiaModel: SSE stream
loop For each data: event
NvidiaModel->>NvidiaModel: Parse delta.reasoning_content/content
NvidiaModel->>Sender: Call with reasoning and content pointers
Sender-->>NvidiaModel: error or nil
end
NvidiaModel->>Sender: Send end-of-stream marker
NvidiaModel-->>Client: nil or error
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Warning Review ran into problems🔥 ProblemsGit: Failed to clone repository. Please run the Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/cli/user_command.go (1)
1774-1779:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winUse chat-specific error text instead of instance-model wording.
At Line 1774 and Line 1779, the message still says
failed to list instance models, which is misleading inChatToModeland makes troubleshooting harder.Suggested fix
- return nil, fmt.Errorf("failed to list instance models: HTTP %d, body: %s", resp.StatusCode, string(resp.Body)) + return nil, fmt.Errorf("failed to chat with model: HTTP %d, body: %s", resp.StatusCode, string(resp.Body)) @@ - return nil, fmt.Errorf("failed to list instance models: invalid JSON (%w)", err) + return nil, fmt.Errorf("failed to chat with model: invalid JSON (%w)", 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/cli/user_command.go` around lines 1774 - 1779, The error strings still say "failed to list instance models" inside the ChatToModel flow; update those fmt.Errorf messages to chat-specific wording (e.g., "failed to list chat models") so errors from ChatToModel are accurate. Specifically, in the fmt.Errorf that reports the HTTP status (the one using resp.StatusCode and resp.Body) and in the fmt.Errorf wrapping json.Unmarshal's error (the one returning "invalid JSON"), change the message prefix to "failed to list chat models" while keeping the existing error details and formatting.
🤖 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 `@internal/entity/models/nvidia.go`:
- Around line 327-329: The Encode method on NvidiaModel currently always returns
an error which will break runtime selection of Nvidia embedding models;
implement Encode(modelName *string, texts []string, apiConfig *APIConfig,
embeddingConfig *EmbeddingConfig) to perform the actual embedding call for
Nvidia (use the same flow other providers use: validate modelName, build request
payload from texts and embeddingConfig, call the Nvidia embeddings endpoint via
the HTTP client configured in APIConfig, handle errors, parse and return
[][]float64 embeddings), or delegate to an existing shared helper used by other
model types; update NvidiaModel.Encode to return the real embeddings and errors
instead of fmt.Errorf("no such method").
- Around line 38-41: NewInstance currently replaces the NvidiaModel.BaseURL with
the incoming baseURL map and loses factory defaults; update
NvidiaModel.NewInstance so it merges n.BaseURL (defaults) with the provided
baseURL overrides instead of overwriting: create a new map starting from
n.BaseURL, copy/overlay keys from the baseURL parameter into it, and assign that
merged map to BaseURL on the returned *NvidiaModel while keeping URLSuffix and
other fields unchanged.
---
Outside diff comments:
In `@internal/cli/user_command.go`:
- Around line 1774-1779: The error strings still say "failed to list instance
models" inside the ChatToModel flow; update those fmt.Errorf messages to
chat-specific wording (e.g., "failed to list chat models") so errors from
ChatToModel are accurate. Specifically, in the fmt.Errorf that reports the HTTP
status (the one using resp.StatusCode and resp.Body) and in the fmt.Errorf
wrapping json.Unmarshal's error (the one returning "invalid JSON"), change the
message prefix to "failed to list chat models" while keeping the existing error
details and formatting.
🪄 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: 3b9ce41a-2c8a-471b-80b5-de0e7c14b1f4
📒 Files selected for processing (4)
conf/models/nvidia.jsoninternal/cli/user_command.gointernal/entity/models/factory.gointernal/entity/models/nvidia.go
| func (n NvidiaModel) NewInstance(baseURL map[string]string) ModelDriver { | ||
| return &NvidiaModel{ | ||
| BaseURL: baseURL, | ||
| URLSuffix: n.URLSuffix, |
There was a problem hiding this comment.
Preserve base URL fallbacks when creating instance drivers.
NewInstance at Line 40 overwrites BaseURL entirely. If caller passes only region overrides, default fallback from the factory config is lost, which can break request routing.
Suggested fix
func (n NvidiaModel) NewInstance(baseURL map[string]string) ModelDriver {
+ merged := make(map[string]string, len(n.BaseURL)+len(baseURL))
+ for k, v := range n.BaseURL {
+ merged[k] = v
+ }
+ for k, v := range baseURL {
+ merged[k] = v
+ }
return &NvidiaModel{
- BaseURL: baseURL,
+ BaseURL: merged,
URLSuffix: n.URLSuffix,
httpClient: &http.Client{📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| func (n NvidiaModel) NewInstance(baseURL map[string]string) ModelDriver { | |
| return &NvidiaModel{ | |
| BaseURL: baseURL, | |
| URLSuffix: n.URLSuffix, | |
| func (n NvidiaModel) NewInstance(baseURL map[string]string) ModelDriver { | |
| merged := make(map[string]string, len(n.BaseURL)+len(baseURL)) | |
| for k, v := range n.BaseURL { | |
| merged[k] = v | |
| } | |
| for k, v := range baseURL { | |
| merged[k] = v | |
| } | |
| return &NvidiaModel{ | |
| BaseURL: merged, | |
| URLSuffix: n.URLSuffix, |
🤖 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/nvidia.go` around lines 38 - 41, NewInstance currently
replaces the NvidiaModel.BaseURL with the incoming baseURL map and loses factory
defaults; update NvidiaModel.NewInstance so it merges n.BaseURL (defaults) with
the provided baseURL overrides instead of overwriting: create a new map starting
from n.BaseURL, copy/overlay keys from the baseURL parameter into it, and assign
that merged map to BaseURL on the returned *NvidiaModel while keeping URLSuffix
and other fields unchanged.
| func (n NvidiaModel) Encode(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([][]float64, error) { | ||
| return nil, fmt.Errorf("no such method") | ||
| } |
There was a problem hiding this comment.
Embedding capability mismatch will fail at runtime.
Encode returns no such method, but this provider is configured with embedding models. Selecting an Nvidia embedding model will fail on invocation.
🤖 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/nvidia.go` around lines 327 - 329, The Encode method
on NvidiaModel currently always returns an error which will break runtime
selection of Nvidia embedding models; implement Encode(modelName *string, texts
[]string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) to perform the
actual embedding call for Nvidia (use the same flow other providers use:
validate modelName, build request payload from texts and embeddingConfig, call
the Nvidia embeddings endpoint via the HTTP client configured in APIConfig,
handle errors, parse and return [][]float64 embeddings), or delegate to an
existing shared helper used by other model types; update NvidiaModel.Encode to
return the real embeddings and errors instead of fmt.Errorf("no such method").
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14623 +/- ##
=======================================
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:
|
…14636) ### What problem does this PR solve? The NVIDIA Go driver added in #14623 has a real chat path, but \`ListModels\` and \`CheckConnection\` are stubs that always return \`no such method\`. So: - The model picker cannot auto-populate available NVIDIA NIM model ids. Users have to type the full id by hand (e.g. \`abacusai/dracarys-llama-3.1-70b-instruct\`). - The "Check connection" button always fails for NVIDIA, even when the base URL is reachable and the API key is accepted. NVIDIA NIM is OpenAI-compatible. \`/v1/models\` works with the same Bearer token used for chat. The \`conf/models/nvidia.json\` file already wires the \`models\` url_suffix, so no config change is needed. ### What this PR includes - \`internal/entity/models/nvidia.go\`: - \`ListModels\` now calls \`GET ${BaseURL}/${URLSuffix.Models}\`, parses \`response.data[*].id\`, and returns the list. Same shape as the moonshot, xai, and openai drivers. - \`CheckConnection\` now calls \`ListModels\` and returns its error. Same pattern xai, moonshot, deepseek, aliyun, and gitee already use. \`Balance\`, \`Encode\`, and \`Rerank\` are still stubs in this PR and can be added in follow-ups. No JSON change. No factory change. No interface change. ### How the implementation works - Region resolution falls back to \`default\` when the supplied region is unknown, so a stray region value does not break a valid request. - The Authorization header is only set when \`apiConfig\` and \`ApiKey\` are non-nil and non-empty. This avoids a nil-pointer dereference and lets self-hosted NIM deployments without a key still work. - Non-200 responses propagate the upstream status line and body so the user sees a real error message. ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue) ### How was this tested? - \`go build ./internal/entity/models/...\` in a clean go 1.25 image (the go.mod minimum) returns exit 0. - The full method set on \`NvidiaModel\` still matches the \`ModelDriver\` interface. - Pattern parity with the existing xai, moonshot, deepseek, aliyun, gitee, and openai drivers. Closes #14635
…nfiniflow#14636) ### What problem does this PR solve? The NVIDIA Go driver added in infiniflow#14623 has a real chat path, but \`ListModels\` and \`CheckConnection\` are stubs that always return \`no such method\`. So: - The model picker cannot auto-populate available NVIDIA NIM model ids. Users have to type the full id by hand (e.g. \`abacusai/dracarys-llama-3.1-70b-instruct\`). - The "Check connection" button always fails for NVIDIA, even when the base URL is reachable and the API key is accepted. NVIDIA NIM is OpenAI-compatible. \`/v1/models\` works with the same Bearer token used for chat. The \`conf/models/nvidia.json\` file already wires the \`models\` url_suffix, so no config change is needed. ### What this PR includes - \`internal/entity/models/nvidia.go\`: - \`ListModels\` now calls \`GET ${BaseURL}/${URLSuffix.Models}\`, parses \`response.data[*].id\`, and returns the list. Same shape as the moonshot, xai, and openai drivers. - \`CheckConnection\` now calls \`ListModels\` and returns its error. Same pattern xai, moonshot, deepseek, aliyun, and gitee already use. \`Balance\`, \`Encode\`, and \`Rerank\` are still stubs in this PR and can be added in follow-ups. No JSON change. No factory change. No interface change. ### How the implementation works - Region resolution falls back to \`default\` when the supplied region is unknown, so a stray region value does not break a valid request. - The Authorization header is only set when \`apiConfig\` and \`ApiKey\` are non-nil and non-empty. This avoids a nil-pointer dereference and lets self-hosted NIM deployments without a key still work. - Non-200 responses propagate the upstream status line and body so the user sees a real error message. ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue) ### How was this tested? - \`go build ./internal/entity/models/...\` in a clean go 1.25 image (the go.mod minimum) returns exit 0. - The full method set on \`NvidiaModel\` still matches the \`ModelDriver\` interface. - Pattern parity with the existing xai, moonshot, deepseek, aliyun, gitee, and openai drivers. Closes infiniflow#14635
### What problem does this PR solve? 1. **Implement `Nvidia` Provider:** Fully support NVIDIA NIM APIs with robust parameter handling (including the `thinking` parameter) and safe URL merging in `NewInstance`. 2. **Fix Misleading CLI Errors:** Corrected a bug in `common_command.go` where failed chat requests inaccurately reported `failed to list instance models`. ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue) - [x] New Feature (non-breaking change which adds functionality)
…nfiniflow#14636) ### What problem does this PR solve? The NVIDIA Go driver added in infiniflow#14623 has a real chat path, but \`ListModels\` and \`CheckConnection\` are stubs that always return \`no such method\`. So: - The model picker cannot auto-populate available NVIDIA NIM model ids. Users have to type the full id by hand (e.g. \`abacusai/dracarys-llama-3.1-70b-instruct\`). - The "Check connection" button always fails for NVIDIA, even when the base URL is reachable and the API key is accepted. NVIDIA NIM is OpenAI-compatible. \`/v1/models\` works with the same Bearer token used for chat. The \`conf/models/nvidia.json\` file already wires the \`models\` url_suffix, so no config change is needed. ### What this PR includes - \`internal/entity/models/nvidia.go\`: - \`ListModels\` now calls \`GET ${BaseURL}/${URLSuffix.Models}\`, parses \`response.data[*].id\`, and returns the list. Same shape as the moonshot, xai, and openai drivers. - \`CheckConnection\` now calls \`ListModels\` and returns its error. Same pattern xai, moonshot, deepseek, aliyun, and gitee already use. \`Balance\`, \`Encode\`, and \`Rerank\` are still stubs in this PR and can be added in follow-ups. No JSON change. No factory change. No interface change. ### How the implementation works - Region resolution falls back to \`default\` when the supplied region is unknown, so a stray region value does not break a valid request. - The Authorization header is only set when \`apiConfig\` and \`ApiKey\` are non-nil and non-empty. This avoids a nil-pointer dereference and lets self-hosted NIM deployments without a key still work. - Non-200 responses propagate the upstream status line and body so the user sees a real error message. ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue) ### How was this tested? - \`go build ./internal/entity/models/...\` in a clean go 1.25 image (the go.mod minimum) returns exit 0. - The full method set on \`NvidiaModel\` still matches the \`ModelDriver\` interface. - Pattern parity with the existing xai, moonshot, deepseek, aliyun, gitee, and openai drivers. Closes infiniflow#14635
What problem does this PR solve?
NvidiaProvider: Fully support NVIDIA NIM APIs with robust parameter handling (including thethinkingparameter) and safe URL merging inNewInstance.common_command.gowhere failed chat requests inaccurately reportedfailed to list instance models.Type of change