Skip to content

Go: implement provider: Nvidia - #14623

Merged
JinHai-CN merged 1 commit into
infiniflow:mainfrom
Haruko386:main
May 7, 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?

  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

  • Bug Fix (non-breaking change which fixes an issue)
  • New Feature (non-breaking change which adds functionality)

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label May 7, 2026
@Haruko386 Haruko386 added the ci Continue Integration label May 7, 2026
@coderabbitai

coderabbitai Bot commented May 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

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

Changes

Nvidia Model Provider Integration

Layer / File(s) Summary
Model Configuration Schema
conf/models/nvidia.json
New Nvidia model registry defining base URL (https://integrate.api.nvidia.com/v1), API endpoints for chat and models, and a list of supported models with name, max_tokens, model_types, and optional thinking configuration.
NvidiaModel Driver Core
internal/entity/models/nvidia.go
Defines NvidiaModel struct with base URL mapping, URL suffix, and HTTP client; provides NewNvidiaModel constructor with timeout and connection pooling configuration, plus NewInstance and Name() methods.
Chat Request Implementation
internal/entity/models/nvidia.go
Implements ChatWithMessages for non-streaming requests (validates input, selects region URL, builds JSON payload with optional thinking, parses choices[0].message.content response) and ChatStreamlyWithSender for streaming (scans SSE events, extracts delta.reasoning_content and delta.content, forwards to callback sender, handles [DONE] marker).
Interface Method Stubs
internal/entity/models/nvidia.go
Placeholder implementations for Encode, Rerank, ListModels, Balance, and CheckConnection returning "no such method" errors.
Factory Registration and Error Handling
internal/entity/models/factory.go, internal/cli/user_command.go
Adds nvidia case to provider dispatch in CreateModelDriver, removes deprecated openai case; improves ChatToModel error classification to detect EOF/timeout conditions and return specific error messages instead of generic failures.

Sequence Diagram

sequenceDiagram
  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
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • infiniflow/ragflow#14532: Implements model provider driver with streaming SSE chat handling, region/base_url routing, and model instance logic.
  • infiniflow/ragflow#14605: Modifies the same model-factory dispatch and adds a concrete provider driver (OpenAI).
  • infiniflow/ragflow#14379: Adds a new cloud model provider implementation and updates the factory to register that provider (Aliyun).

Suggested labels

size:XL

Poem

🐰 A rabbit hops toward Nvidia's door,
With models, APIs, and configs galore!
Chat streams and responses, both swift and clean,
Error messages sharper than ever seen!
Factory routing, SSE delight—
The provider integration feels just right! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: implementing support for the Nvidia provider in the Go codebase.
Description check ✅ Passed The description includes both required sections (problem statement and type of change) with clear explanations of the bug fix and new feature being added.
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.

Warning

Review ran into problems

🔥 Problems

Git: Failed to clone repository. Please run the @coderabbitai full review command to re-trigger a full review. If the issue persists, set path_filters to include or exclude specific files.


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 marked this pull request as draft May 7, 2026 05:33
@Haruko386
Haruko386 marked this pull request as ready for review May 7, 2026 05:33

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

Use 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 in ChatToModel and 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

📥 Commits

Reviewing files that changed from the base of the PR and between 911671c and 10a6222.

📒 Files selected for processing (4)
  • conf/models/nvidia.json
  • internal/cli/user_command.go
  • internal/entity/models/factory.go
  • internal/entity/models/nvidia.go

Comment on lines +38 to +41
func (n NvidiaModel) NewInstance(baseURL map[string]string) ModelDriver {
return &NvidiaModel{
BaseURL: baseURL,
URLSuffix: n.URLSuffix,

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

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.

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

Comment on lines +327 to +329
func (n NvidiaModel) Encode(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([][]float64, error) {
return nil, 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

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

codecov Bot commented May 7, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (b8b7415) to head (10a6222).
⚠️ Report is 1 commits behind head on main.

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.
📢 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 078ea3b into infiniflow:main May 7, 2026
1 check passed
@coderabbitai coderabbitai Bot mentioned this pull request May 7, 2026
2 tasks done
JinHai-CN pushed a commit that referenced this pull request May 8, 2026
…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
pekar9781 pushed a commit to pekar9781/ragflow that referenced this pull request May 8, 2026
…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
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?

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)
Ricardo-M-L pushed a commit to Ricardo-M-L/ragflow that referenced this pull request Aug 17, 2026
…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
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