Repository navigation
Go: implement Encode (embeddings) in NVIDIA driver - #14700
Conversation
|
ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughThis PR implements NVIDIA embeddings by adding the ChangesNVIDIA Embeddings Implementation
Sequence DiagramsequenceDiagram
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)
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related issues
Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 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. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
internal/entity/models/nvidia.go (1)
333-338: ⚡ Quick winSimplify
Embeddingto[]float64and eliminate the type switch.
encoding/jsoncoerces all JSON numbers intofloat64when parsed into aninterface{}, so thecase float32:branch in the type switch at lines 419–426 is dead code and can never be reached. Declaring the field as[]float64directly letsjson.Unmarshalpopulate 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
📒 Files selected for processing (2)
conf/models/nvidia.jsoninternal/entity/models/nvidia.go
Haruko386
left a comment
There was a problem hiding this comment.
Hi @bittoby, thank you for your contribution, would you like to add some embedding model for nvidia provider plz
| }, | ||
| "url_suffix": { | ||
| "chat": "chat/completions", | ||
| "models": "models" | ||
| "models": "models", | ||
| "embedding": "embeddings" | ||
| }, | ||
| "class": "nvidia", | ||
| "models": [ |
There was a problem hiding this comment.
Add some supported model for nvidia provider plz
|
@Haruko386 I've updated based on your feedback. Could you pls review again? Thanks |
|
@bittoby Encode interface is updated, would you please update your implementation accordingly? please refer to #14735 |
|
@bittoby Refer to the CLI usage in #14736, would you please provide the CLI embedding test result as below? |
|
@JinHai-CN done. CLI test result on |
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
### 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
What problem does this PR solve?
The NVIDIA Go driver in
internal/entity/models/nvidia.goshipped with a stubEncodemethod that returned
no such method.conf/models/nvidia.jsonalready listsnvidia/llama-3.2-nemoretriever-1b-vlm-embed-v1as an embedding model, but the conf hadno
embeddingURL suffix, so the picker had nothing wired even ifEncodeworked.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/embeddingsand uses an OpenAI-compatible requestbody extended with the NVIDIA-specific
input_typeandtruncatefields. Several otherGo drivers already implement
Encode(siliconflow, zhipu-ai, aliyun), so the interfaceand the pattern are well-established.
This PR fills the gap.
What this PR includes
conf/models/nvidia.json: declare theembeddingURL suffix alongside the existingchatandmodelsentries. The embedding model entry was already present, so nomodel addition is needed.
internal/entity/models/nvidia.go: replace theEncodestub with a realimplementation. 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
apiConfigand the API key, validates the model name, resolves the regionwith a default fallback (matching the pattern the merged
ListModelsandCheckConnectionpaths in this driver already use), and builds the URL fromBaseURL[region] + URLSuffix.Embedding.inputarray, with theNVIDIA-specific
input_type: "query",encoding_format: "float", andtruncate: "END"fields, mirroring the Python
NvidiaEmbedreference.data[*].embeddingand copies each slice into[][]float64indexed bydata[*].indexso the output order matches the input order even if the API returnsitems in a different order.
float64andfloat32element types.[][]float64{}with no HTTP call.slot is still nil.
Type of change
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.gois clean.NvidiaModelstill matches theModelDriverinterface.Encode(Go: implement Encode (embeddings) in Aliyun driver #14647).Closes #14699