Skip to content

Go: implement Encode (embeddings) in NVIDIA driver - #14700

Merged
JinHai-CN merged 5 commits into
infiniflow:mainfrom
Crystora:feat/go-nvidia-encode
May 11, 2026
Merged

JinHai-CN merged 5 commits into
infiniflow:mainfrom
Crystora:feat/go-nvidia-encode

Conversation

@Crystora

@Crystora Crystora commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

The NVIDIA Go driver in internal/entity/models/nvidia.go shipped with a stub Encode
method that returned no such method. conf/models/nvidia.json already lists
nvidia/llama-3.2-nemoretriever-1b-vlm-embed-v1 as an embedding model, but the conf had
no embedding URL suffix, so the picker had nothing wired even if Encode worked.

A tenant who wanted to use NVIDIA NIM for chat (already working) and embeddings from a
single provider could not, even though the upstream endpoint is public at
https://integrate.api.nvidia.com/v1/embeddings and uses an OpenAI-compatible request
body extended with the NVIDIA-specific input_type and truncate fields. Several other
Go drivers already implement Encode (siliconflow, zhipu-ai, aliyun), so the interface
and the pattern are well-established.

This PR fills the gap.

What this PR includes

  • conf/models/nvidia.json: declare the embedding URL suffix alongside the existing
    chat and models entries. The embedding model entry was already present, so no
    model addition is needed.
  • internal/entity/models/nvidia.go: replace the Encode stub with a real
    implementation. Adds a small local response type that matches the OpenAI-compatible
    shape NVIDIA NIM returns.

No factory change. No interface change.

How the driver works

  • Validates apiConfig and the API key, validates the model name, resolves the region
    with a default fallback (matching the pattern the merged ListModels and
    CheckConnection paths in this driver already use), and builds the URL from
    BaseURL[region] + URLSuffix.Embedding.
  • Sends all input texts in one request as the input array, with the
    NVIDIA-specific input_type: "query", encoding_format: "float", and truncate: "END"
    fields, mirroring the Python NvidiaEmbed reference.
  • Parses data[*].embedding and copies each slice into [][]float64 indexed by
    data[*].index so the output order matches the input order even if the API returns
    items in a different order.
  • Handles both float64 and float32 element types.
  • Empty input returns [][]float64{} with no HTTP call.
  • Non-200 responses propagate the upstream status line and body.
  • A final pass checks every input slot got a vector and returns a clear error if any
    slot is still nil.
  • Per-call 30s context deadline so a slow call cannot block forever.

Type of change

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

How was this tested?

  • go build ./internal/entity/models/... returns exit 0.
  • go vet ./internal/entity/models/... is clean.
  • gofmt -l internal/entity/models/nvidia.go is clean.
  • The full method set on NvidiaModel still matches the ModelDriver interface.
  • Pattern parity with the just-merged Aliyun Encode (Go: implement Encode (embeddings) in Aliyun driver #14647).

Closes #14699

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

coderabbitai Bot commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack
No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 491d34db-be71-48ab-9ea4-973bd1506593

📥 Commits

Reviewing files that changed from the base of the PR and between 571ab37 and c92c37a.

📒 Files selected for processing (1)
  • internal/entity/models/nvidia.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/entity/models/nvidia.go

📝 Walkthrough

Walkthrough

This PR implements NVIDIA embeddings by adding the "embedding" URL suffix to the NVIDIA configuration and replacing the stubbed Encode method with a complete implementation that validates inputs, constructs a 30-second-timeout POST request to NVIDIA's embeddings endpoint, parses the response, and returns ordered embedding vectors.

Changes

NVIDIA Embeddings Implementation

Layer / File(s) Summary
Embeddings URL Configuration & Models
conf/models/nvidia.json
Adds "embedding": "embeddings" to url_suffix and several embedding-only model entries (e.g., baai/bge-m3, nvidia/llama-3.2-nv-embedqa-1b-v2, nvidia/nv-embed-*, snowflake/arctic-embed-l).
Embeddings Response Schema
internal/entity/models/nvidia.go
Introduces internal nvidiaEmbeddingResponse struct with Data items containing per-item Index and Embedding fields for API response parsing.
Encode Method Implementation
internal/entity/models/nvidia.go
Implements NvidiaModel.Encode with input/API validation, regional base URL resolution, context-bounded POST request (30s timeout), response unmarshalling, float32/float64 conversion, index bounds checking, and missing embedding detection. Adds context import for timeout support.

Sequence Diagram

sequenceDiagram
  participant Client
  participant Encode as NvidiaModel.Encode
  participant NvidiaAPI as NVIDIA API
  Client->>Encode: Encode(texts, model)
  Encode->>Encode: Validate inputs & API config
  Encode->>Encode: Resolve regional base URL
  Encode->>NvidiaAPI: POST /embeddings (30s timeout)
  NvidiaAPI-->>Encode: {data: [{index, embedding}]}
  Encode->>Encode: Parse & convert to float64
  Encode->>Encode: Validate indices & bounds
  Encode-->>Client: [][]float64 (input order)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

  • #14697: Similar Encode implementation pattern for another provider; shares request/timeout/response parsing approach.

Possibly related PRs

  • infiniflow/ragflow#14437: The main PR implements the new Encode(modelName, texts, apiConfig, embeddingConfig) embedding method for the NvidiaModel, aligning with refactors that standardize Encode across drivers.
  • infiniflow/ragflow#14647: Implements Encode for another provider and adds embedding model entries; similar driver work.

Suggested labels

ci, size:M

Suggested reviewers

  • Haruko386

Poem

🐰 I hopped through configs, code, and test,
Found embeddings where stubs once rest.
Vectors aligned, indices bless,
NVIDIA singing—no more guess.
Hooray for kernels and rabbit zest!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: implementing the Encode method (embeddings support) in the NVIDIA Go driver.
Description check ✅ Passed The description provides comprehensive context including problem statement, solution details, implementation approach, testing notes, and closes issue #14699. All required template sections are addressed.
Linked Issues check ✅ Passed The PR implementation addresses all objectives from issue #14699: adds embedding URL suffix to conf/models/nvidia.json, implements full Encode method with validation, 30s timeout, proper response parsing, and error handling [#14699].
Out of Scope Changes check ✅ Passed All changes are directly scoped to the linked issue #14699: only conf/models/nvidia.json and internal/entity/models/nvidia.go are modified with no extraneous changes beyond the stated embedding implementation.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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


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

❤️ Share

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

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

🧹 Nitpick comments (1)
internal/entity/models/nvidia.go (1)

333-338: ⚡ Quick win

Simplify Embedding to []float64 and eliminate the type switch.

encoding/json coerces all JSON numbers into float64 when parsed into an interface{}, so the case float32: branch in the type switch at lines 419–426 is dead code and can never be reached. Declaring the field as []float64 directly lets json.Unmarshal populate it without a type assertion loop at all.

♻️ Proposed simplification
 type nvidiaEmbeddingResponse struct {
 	Data []struct {
 		Index     int     `json:"index"`
-		Embedding []interface{} `json:"embedding"`
+		Embedding []float64 `json:"embedding"`
 	} `json:"data"`
 }

Then the per-item conversion loop simplifies to:

-		vec := make([]float64, len(item.Embedding))
-		for j, v := range item.Embedding {
-			switch val := v.(type) {
-			case float64:
-				vec[j] = val
-			case float32:
-				vec[j] = float64(val)
-			default:
-				return nil, fmt.Errorf("unexpected embedding value type at item %d index %d", item.Index, j)
-			}
-		}
-		embeddings[item.Index] = vec
+		embeddings[item.Index] = item.Embedding
🤖 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 333 - 338, The
nvidiaEmbeddingResponse struct's Data[].Embedding should be changed from
[]interface{} to []float64 and the manual per-item type-switch conversion
removed: update the struct definition (nvidiaEmbeddingResponse →
Data[].Embedding []float64), eliminate the type-switch code that handles
float32/float64, and where the code previously iterated and asserted each item
(the conversion block that checks for float32/float64) simply use the []float64
slice directly (or cast to []float64) to build your []float64 embeddings; remove
the dead float32 branch and adjust any callers expecting []interface{} to accept
[]float64.
🤖 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.

Nitpick comments:
In `@internal/entity/models/nvidia.go`:
- Around line 333-338: The nvidiaEmbeddingResponse struct's Data[].Embedding
should be changed from []interface{} to []float64 and the manual per-item
type-switch conversion removed: update the struct definition
(nvidiaEmbeddingResponse → Data[].Embedding []float64), eliminate the
type-switch code that handles float32/float64, and where the code previously
iterated and asserted each item (the conversion block that checks for
float32/float64) simply use the []float64 slice directly (or cast to []float64)
to build your []float64 embeddings; remove the dead float32 branch and adjust
any callers expecting []interface{} to accept []float64.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: a1e7c4e3-24a7-4e2b-aa8c-34cb76992e27

📥 Commits

Reviewing files that changed from the base of the PR and between 5e96c5c and 87f0d7e.

📒 Files selected for processing (2)
  • conf/models/nvidia.json
  • internal/entity/models/nvidia.go

@Haruko386 Haruko386 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Hi @bittoby, thank you for your contribution, would you like to add some embedding model for nvidia provider plz

Comment thread conf/models/nvidia.json
Comment on lines 5 to 12
},
"url_suffix": {
"chat": "chat/completions",
"models": "models"
"models": "models",
"embedding": "embeddings"
},
"class": "nvidia",
"models": [

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Add some supported model for nvidia provider plz

@Crystora

Crystora commented May 9, 2026 •

Copy link
Copy Markdown
Contributor Author

@Haruko386 I've updated based on your feedback. Could you pls review again? Thanks

@Haruko386 Haruko386 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@bittoby LGTM

@JinHai-CN

Copy link
Copy Markdown
Member

@bittoby Encode interface is updated, would you please update your implementation accordingly? please refer to #14735

@JinHai-CN JinHai-CN added the ci Continue Integration label May 9, 2026
@JinHai-CN

Copy link
Copy Markdown
Member

@bittoby Refer to the CLI usage in #14736, would you please provide the CLI embedding test result as below?

RAGFlow(user)> embed text 'what is rag' 'who are you' with 'embedding-3@test@zhipu-ai' dimension 16;
+-----------+-------+
| dimension | index |
+-----------+-------+
| 16        | 0     |
| 16        | 1     |
+-----------+-------+

@Crystora

Copy link
Copy Markdown
Contributor Author

@JinHai-CN done. CLI test result on nvidia/llama-3.2-nv-embedqa-1b-v2:

RAGFlow(user)> embed text 'what is rag' 'who are you' with 'nvidia/llama-3.2-nv-embedqa-1b-v2@test@nvidia' dimension 16;
+-----------+-------+
| dimension | index |
+-----------+-------+
| 16        | 0     |
| 16        | 1     |
+-----------+-------+

@JinHai-CN
JinHai-CN marked this pull request as draft May 11, 2026 02:58
@JinHai-CN
JinHai-CN marked this pull request as ready for review May 11, 2026 02:58
@codecov

codecov Bot commented May 11, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (7931b69) to head (c92c37a).
⚠️ Report is 20 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14700   +/-   ##
=======================================
  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 4b96362 into infiniflow:main May 11, 2026
2 checks passed
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?

The NVIDIA Go driver in `internal/entity/models/nvidia.go` shipped with
a stub `Encode`
method that returned `no such method`. `conf/models/nvidia.json` already
lists
`nvidia/llama-3.2-nemoretriever-1b-vlm-embed-v1` as an embedding model,
but the conf had
no `embedding` URL suffix, so the picker had nothing wired even if
`Encode` worked.

A tenant who wanted to use NVIDIA NIM for chat (already working) and
embeddings from a
single provider could not, even though the upstream endpoint is public
at
`https://integrate.api.nvidia.com/v1/embeddings` and uses an
OpenAI-compatible request
body extended with the NVIDIA-specific `input_type` and `truncate`
fields. Several other
Go drivers already implement `Encode` (siliconflow, zhipu-ai, aliyun),
so the interface
and the pattern are well-established.

This PR fills the gap.

### What this PR includes

* `conf/models/nvidia.json`: declare the `embedding` URL suffix
alongside the existing
`chat` and `models` entries. The embedding model entry was already
present, so no
  model addition is needed.
* `internal/entity/models/nvidia.go`: replace the `Encode` stub with a
real
implementation. Adds a small local response type that matches the
OpenAI-compatible
  shape NVIDIA NIM returns.

No factory change. No interface change.

### How the driver works

* Validates `apiConfig` and the API key, validates the model name,
resolves the region
with a default fallback (matching the pattern the merged `ListModels`
and
`CheckConnection` paths in this driver already use), and builds the URL
from
  `BaseURL[region] + URLSuffix.Embedding`.
* Sends all input texts in one request as the `input` array, with the
NVIDIA-specific `input_type: "query"`, `encoding_format: "float"`, and
`truncate: "END"`
  fields, mirroring the Python `NvidiaEmbed` reference.
* Parses `data[*].embedding` and copies each slice into `[][]float64`
indexed by
`data[*].index` so the output order matches the input order even if the
API returns
  items in a different order.
* Handles both `float64` and `float32` element types.
* Empty input returns `[][]float64{}` with no HTTP call.
* Non-200 responses propagate the upstream status line and body.
* A final pass checks every input slot got a vector and returns a clear
error if any
  slot is still nil.
* Per-call 30s context deadline so a slow call cannot block forever.

### Type of change

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

### How was this tested?

* `go build ./internal/entity/models/...` returns exit 0.
* `go vet ./internal/entity/models/...` is clean.
* `gofmt -l internal/entity/models/nvidia.go` is clean.
* The full method set on `NvidiaModel` still matches the `ModelDriver`
interface.
* Pattern parity with the just-merged Aliyun `Encode` (infiniflow#14647).

Closes infiniflow#14699
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.

[Feature Request]: Implement Encode (embeddings) in the NVIDIA Go driver

3 participants