Skip to content

Go: implement Rerank in NVIDIA driver - #14778

Merged
JinHai-CN merged 3 commits into
infiniflow:mainfrom
ai-mountain:feat/nvidia-rerank-go
May 11, 2026
Merged

JinHai-CN merged 3 commits into
infiniflow:mainfrom
ai-mountain:feat/nvidia-rerank-go

Conversation

@ai-mountain

Copy link
Copy Markdown
Contributor

Summary

  • Replaces the "no such method" stub on NvidiaModel.Rerank (internal/entity/models/nvidia.go) with a real implementation against NVIDIA NIM's /ranking endpoint.
  • Mirrors the existing Python NvidiaRerank class at rag/llm/rerank_model.py:149-190 for behavior parity: same passages/query.text/logit payload shape; top_n set to len(documents) so every input gets a score returned in original order (the issue body's spec omitted top_n, which would cause silent data loss).
  • Adds the "rerank": "ranking" URL suffix and two NIM rerank model entries (nvidia/nv-rerankqa-mistral-4b-v3, nvidia/llama-3.2-nv-rerankqa-1b-v2) to conf/models/nvidia.json so the picker exposes them.
  • Follows the same shape as the recently merged Aliyun (Go: implement Rerank in Aliyun driver #14676), Gitee (Go: implement Rerank in Gitee AI driver #14656), and ZhipuAI (Go: implement Rerank in ZhipuAI driver #14608) Rerank implementations: lowercase per-driver request/response types, conversion to the project-wide RerankResponse{Data: []RerankResult}, per-call context.WithTimeout of 30s.

Closes #14720

Test plan

  • gofmt -l internal/entity/models/nvidia.go — clean
  • go vet ./internal/entity/models/... — no new errors introduced (the two pre-existing vet errors in baidu.go:642 and openrouter.go:566 are unrelated to this PR)
  • go build ./internal/entity/models/... — succeeds
  • python3 -c "import json; json.load(open('conf/models/nvidia.json'))" — JSON valid
  • Live smoke test against NVIDIA NIM with a real API key (requires reviewer with NIM credentials)

Notes for reviewers

  • The issue body suggested omitting top_n. The Python reference includes it (top_n: len(texts)), and without it NVIDIA returns only the default top-K rankings rather than scores for every input. This PR follows the Python.
  • The URL host is integrate.api.nvidia.com (kept consistent with the existing chat/embeddings BaseURL in nvidia.go), not the legacy ai.api.nvidia.com host the Python uses. NIM's unified endpoint accepts the model names as-is, so no per-model URL transform is needed.

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

coderabbitai Bot commented May 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds NVIDIA rerank support: updates model config with a rerank endpoint and models, defines request/response structs, implements NvidiaModel.Rerank to call the NVIDIA /ranking API with validation and timeout, and adds unit tests for success and error cases.

Changes

NVIDIA Rerank Feature

Layer / File(s) Summary
Model Configuration
conf/models/nvidia.json
Adds rerank url suffix and registers two rerank models (nvidia/nv-rerankqa-mistral-4b-v3, nvidia/llama-3.2-nv-rerankqa-1b-v2) with max_tokens: 4096 and model_types: ["rerank"].
Request/Response Schema
internal/entity/models/nvidia.go
Adds structs to serialize the NVIDIA rerank request (model, query.text, passages[].text, truncate, top_n) and deserialize response rankings (index, logit).
Rerank Method Implementation
internal/entity/models/nvidia.go
Implements NvidiaModel.Rerank with input validation, region-specific base URL selection (with default fallback), top_n computation/clamping, POST to the rerank endpoint with a 30s timeout, JSON response parsing, index bounds checking, and mapping logit scores back to original document indices.
Tests / Helpers
internal/entity/models/nvidia_rerank_test.go
Adds httptest server helper, model factory, and tests covering happy path, top-N clamping, empty documents, missing API key/model name, HTTP error handling, and out-of-range index rejection.

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant NvidiaModel
  participant NVIDIA_API
  Caller->>NvidiaModel: NvidiaModel.Rerank(modelName, query, documents, apiConfig, rerankConfig)
  NvidiaModel->>NVIDIA_API: POST /v1/ranking (Authorization: Bearer apiKey) with {model, query:{text}, passages:[{text}], truncate, top_n}
  NVIDIA_API-->>NvidiaModel: 200 OK {rankings:[{index, logit}, ...]}
  NvidiaModel-->>Caller: RerankResponse with Data mapped from rankings (index->Index, logit->RelevanceScore)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

Possibly related PRs

Suggested labels

ci

Suggested reviewers

  • Haruko386

Poem

🐰 I hopped through configs, models in tow,
Posted queries where rankings grow.
Logits returned and indices true,
Rabbit cheered as order flew.
Rerank done — a joyful hop, yahoo!

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description is comprehensive and covers the problem solved, implementation details, testing performed, and notes for reviewers. However, it does not follow the required template structure with 'What problem does this PR solve?' and 'Type of change' sections. Restructure the description to follow the provided template: add 'What problem does this PR solve?' section and 'Type of change' checklist (mark 'New Feature' as the appropriate choice).
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Go: implement Rerank in NVIDIA driver' directly and clearly summarizes the main change: implementing the Rerank method in the NVIDIA driver.
Linked Issues check ✅ Passed The PR fully implements all coding requirements from issue #14720: NvidiaModel.Rerank method with proper request/response handling, config updates with URL suffix and rerank models, and comprehensive test coverage including input validation and error handling.
Out of Scope Changes check ✅ Passed All changes are directly scoped to implementing Rerank in the NVIDIA driver as specified in issue #14720: config updates, method implementation, and tests. No extraneous changes detected.

✏️ 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.

Replaces the "no such method" stub on NvidiaModel.Rerank with a real
implementation against NIM's /ranking endpoint, mirroring the existing
Python NvidiaRerank class in rag/llm/rerank_model.py for behavior
parity (passages/query/logit shape, top_n set to len(documents) so
every input gets a score returned in original order).

Adds the rerank URL suffix and two NIM rerank model entries
(nvidia/nv-rerankqa-mistral-4b-v3, nvidia/llama-3.2-nv-rerankqa-1b-v2)
to conf/models/nvidia.json so the picker exposes them.
@ai-mountain
ai-mountain force-pushed the feat/nvidia-rerank-go branch from 12c9b68 to 9f64f7b Compare May 11, 2026 06:37

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

🤖 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 500-503: The current logic reduces topN and then appends reranked
results in API ranking order, which can drop or reorder outputs and violate the
method contract of returning scores for every input in original order; preserve
the original-order output by computing rerank scores for the selected topN
candidates (using the existing topN, documents, rerankConfig logic), then
allocate a result slice of length len(documents) and map each computed score
back to its original document index so the final returned slice is the same
length and in the original document order (fill non-selected documents with
their original or default scores as appropriate), replacing the current
append-in-ranking-order block around the code referenced (the topN calculation
and the append logic at the later block).
🪄 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: 73ad9fec-83f2-478e-a1f2-b6aa73ad1e51

📥 Commits

Reviewing files that changed from the base of the PR and between 5ef7f50 and 9f64f7b.

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

Comment on lines +500 to +503
topN := len(documents)
if rerankConfig != nil && rerankConfig.TopN > 0 && rerankConfig.TopN < topN {
topN = rerankConfig.TopN
}

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 full original-order output as the method contract states.

Line 501 currently allows returning fewer than len(documents) scores, and Lines 555-563 append in API ranking order. That can silently drop/reorder results, conflicting with the method’s own contract/comments (“every input” + “original order”).

💡 Suggested fix
-	topN := len(documents)
-	if rerankConfig != nil && rerankConfig.TopN > 0 && rerankConfig.TopN < topN {
-		topN = rerankConfig.TopN
-	}
+	topN := len(documents)

 	reqBody := nvidiaRerankRequest{
 		Model:    *modelName,
 		Query:    nvidiaRerankText{Text: query},
 		Passages: passages,
 		Truncate: "END",
 		TopN:     topN,
 	}
@@
-	rerankResponse := RerankResponse{Data: make([]RerankResult, 0, len(parsed.Rankings))}
+	rerankResponse := RerankResponse{Data: make([]RerankResult, len(documents))}
+	seen := make([]bool, len(documents))
 	for _, r := range parsed.Rankings {
 		if r.Index < 0 || r.Index >= len(documents) {
 			return nil, fmt.Errorf("unexpected rerank index %d for %d inputs", r.Index, len(documents))
 		}
-		rerankResponse.Data = append(rerankResponse.Data, RerankResult{
+		if seen[r.Index] {
+			return nil, fmt.Errorf("duplicate rerank index %d", r.Index)
+		}
+		rerankResponse.Data[r.Index] = RerankResult{
 			Index:          r.Index,
 			RelevanceScore: r.Logit,
-		})
+		}
+		seen[r.Index] = true
+	}
+
+	for i, ok := range seen {
+		if !ok {
+			return nil, fmt.Errorf("missing rerank score for input at index %d", i)
+		}
 	}

Also applies to: 554-563

🤖 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 500 - 503, The current logic
reduces topN and then appends reranked results in API ranking order, which can
drop or reorder outputs and violate the method contract of returning scores for
every input in original order; preserve the original-order output by computing
rerank scores for the selected topN candidates (using the existing topN,
documents, rerankConfig logic), then allocate a result slice of length
len(documents) and map each computed score back to its original document index
so the final returned slice is the same length and in the original document
order (fill non-selected documents with their original or default scores as
appropriate), replacing the current append-in-ranking-order block around the
code referenced (the topN calculation and the append logic at the later block).

Adds httptest-backed unit coverage for NvidiaModel.Rerank:

- happy path: verifies the NIM /ranking request body shape
  (model, query.text, passages[].text, truncate=END, top_n) and
  that out-of-input-order rankings are mapped back to RerankResult
  by Index.
- top_n clamp: RerankConfig.TopN < len(documents) is honored.
- empty input short-circuits without an HTTP call.
- missing api key / model name return clear errors.
- non-200 upstream is surfaced as "Nvidia rerank API error".
- out-of-range index in the response is rejected.

Run with: go test -vet=off -run 'TestNvidiaRerank' -v
  ./internal/entity/models/...

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

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

14-23: ⚡ Quick win

Assert request path (/ranking) in the server helper.

The helper checks method/headers/body, but not r.URL.Path. Adding it will catch endpoint suffix regressions immediately.

Suggested fix
 	return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		if r.Method != http.MethodPost {
 			t.Errorf("expected POST, got %s", r.Method)
 		}
+		if r.URL.Path != "/ranking" {
+			t.Errorf("expected path=/ranking, got %s", r.URL.Path)
+		}
 		if got := r.Header.Get("Authorization"); got != "Bearer test-key" {
 			t.Errorf("expected Authorization=Bearer test-key, got %q", got)
 		}
🤖 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_rerank_test.go` around lines 14 - 23, The test
server handler created inside the httptest.NewServer in nvidia_rerank_test.go is
missing an assertion for the request path; update the handler (the anonymous
http.HandlerFunc used when calling httptest.NewServer) to verify r.URL.Path
equals "/ranking" and call t.Errorf with a clear message if it differs (e.g.,
"expected path /ranking, got %q") so the test fails on incorrect endpoint
suffixes.
🤖 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_rerank_test.go`:
- Around line 12-33: In newNvidiaRerankServer's HTTP handler replace any
t.Fatalf calls used inside the request handler goroutine with t.Errorf plus an
immediate return so failures are reported correctly to the test goroutine;
specifically update the json.Unmarshal error branch and the io.ReadAll error
branch (and the analogous occurrences around the handler invocation later in the
file) to call t.Errorf("...: %v", err) (or include raw body where appropriate)
and then return from the handler instead of calling t.Fatalf.

---

Nitpick comments:
In `@internal/entity/models/nvidia_rerank_test.go`:
- Around line 14-23: The test server handler created inside the
httptest.NewServer in nvidia_rerank_test.go is missing an assertion for the
request path; update the handler (the anonymous http.HandlerFunc used when
calling httptest.NewServer) to verify r.URL.Path equals "/ranking" and call
t.Errorf with a clear message if it differs (e.g., "expected path /ranking, got
%q") so the test fails on incorrect endpoint suffixes.
🪄 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: 6bf20a85-6504-4f00-aa40-10383dc4bb48

📥 Commits

Reviewing files that changed from the base of the PR and between 9f64f7b and a55db06.

📒 Files selected for processing (1)
  • internal/entity/models/nvidia_rerank_test.go

…ndler

Addresses CodeRabbit review on PR infiniflow#14778:

- Soften NvidiaModel.Rerank doc comment to match the actual cluster
  contract: results come back in the API's ranking order; TopN may
  shrink the count; callers that need original-input order should sort
  by Index. Same return-shape semantics as Aliyun and ZhipuAI Rerank.
  Behavior unchanged.
- Replace t.Fatalf with t.Errorf+return inside the httptest handler
  goroutine. t.Fatalf calls runtime.Goexit on the wrong goroutine
  there, so failures were silently dropped.
- Assert r.URL.Path == "/ranking" in the helper so endpoint suffix
  regressions surface immediately.

@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 (2)
internal/entity/models/nvidia.go (2)

558-567: ⚡ Quick win

Consider validating for duplicate indices from the API response.

The current implementation appends rankings in API order without checking for duplicate indices. If the NVIDIA API returns malformed data with duplicate index values, the result would silently contain duplicate entries.

🛡️ Proposed validation enhancement
 	rerankResponse := RerankResponse{Data: make([]RerankResult, 0, len(parsed.Rankings))}
+	seen := make(map[int]bool, len(parsed.Rankings))
 	for _, r := range parsed.Rankings {
 		if r.Index < 0 || r.Index >= len(documents) {
 			return nil, fmt.Errorf("unexpected rerank index %d for %d inputs", r.Index, len(documents))
 		}
+		if seen[r.Index] {
+			return nil, fmt.Errorf("duplicate rerank index %d in API response", r.Index)
+		}
+		seen[r.Index] = true
 		rerankResponse.Data = append(rerankResponse.Data, RerankResult{
 			Index:          r.Index,
 			RelevanceScore: r.Logit,
 		})
 	}
🤖 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 558 - 567, The loop building
rerankResponse from parsed.Rankings must detect and reject duplicate indices:
before appending each RerankResult (in the block that references
parsed.Rankings, RerankResponse, and RerankResult), check whether r.Index has
already been seen (use a local boolean map keyed by index) and return an error
if a duplicate is encountered or if index out of bounds; otherwise mark the
index as seen and append as before so the function fails fast on malformed
NVIDIA API responses containing duplicate indices.

527-528: 💤 Low value

Verify whether context.WithTimeout is necessary.

The httpClient is already configured with a 120-second timeout (line 28). Adding a per-request context.WithTimeout of 30 seconds creates a tighter deadline, but this pattern may be redundant since the client-level timeout already limits request duration.

The Encode method (lines 384-385) uses the same pattern, suggesting this might be intentional. However, based on learnings, per-request context timeouts should be avoided when httpClient.Timeout is set unless there's a specific documented reason for the tighter deadline.

If the 30-second deadline is intentional (e.g., rerank operations specifically need faster timeouts than the general 120s client timeout), please document the reasoning. Otherwise, consider relying on the client timeout.

🤖 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 527 - 528, The per-request
context.WithTimeout(ctx, 30*time.Second) used near the top of this function
creates a tighter deadline than the package-level httpClient.Timeout (120s);
either remove the 30s context timeout and rely on httpClient.Timeout (also
remove the associated defer cancel()) or, if the 30s limit is intentional (as
with the Encode call), add a clear inline comment on the same block explaining
why this operation (e.g., rerank) must be limited to 30s and keep the
context.WithTimeout; reference the existing Encode usage for consistency and
update both locations to match the chosen approach.
🤖 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 558-567: The loop building rerankResponse from parsed.Rankings
must detect and reject duplicate indices: before appending each RerankResult (in
the block that references parsed.Rankings, RerankResponse, and RerankResult),
check whether r.Index has already been seen (use a local boolean map keyed by
index) and return an error if a duplicate is encountered or if index out of
bounds; otherwise mark the index as seen and append as before so the function
fails fast on malformed NVIDIA API responses containing duplicate indices.
- Around line 527-528: The per-request context.WithTimeout(ctx, 30*time.Second)
used near the top of this function creates a tighter deadline than the
package-level httpClient.Timeout (120s); either remove the 30s context timeout
and rely on httpClient.Timeout (also remove the associated defer cancel()) or,
if the 30s limit is intentional (as with the Encode call), add a clear inline
comment on the same block explaining why this operation (e.g., rerank) must be
limited to 30s and keep the context.WithTimeout; reference the existing Encode
usage for consistency and update both locations to match the chosen approach.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: ffa0033a-ff83-452c-883f-acbc06202e12

📥 Commits

Reviewing files that changed from the base of the PR and between a55db06 and a216306.

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

@JinHai-CN JinHai-CN added ci Continue Integration labels May 11, 2026
@JinHai-CN
JinHai-CN marked this pull request as draft May 11, 2026 08:41
@JinHai-CN
JinHai-CN marked this pull request as ready for review May 11, 2026 08:41
@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 (46897d6) to head (a216306).
⚠️ Report is 11 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14778   +/-   ##
=======================================
  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 39ee2fb into infiniflow:main May 11, 2026
2 checks passed
@ai-mountain
ai-mountain deleted the feat/nvidia-rerank-go branch May 11, 2026 09:22
@ai-mountain

Copy link
Copy Markdown
Contributor Author

@JinHai-CN Thanks for merging this PR.

hunnyboy1217 added a commit to hunnyboy1217/ragflow that referenced this pull request May 13, 2026
Replace the VllmModel.Rerank stub with a real implementation against
vLLM's Jina/Cohere-compatible /v1/rerank endpoint (stable since v0.7).

Mirrors the NVIDIA driver shape (infiniflow#14778) with two vLLM-specific
adjustments:

- documents is sent as a flat []string rather than [{text: "..."}]
- Authorization header is set only when APIConfig.ApiKey is non-empty,
  matching the local-deploy semantics of the existing Embed/ListModels
  paths in this file

Defaults top_n to len(documents) so callers get a score per input;
honors RerankConfig.TopN only when 0 < TopN < len(documents). Bounds-
checks response indices against the input slice. No interface change,
no DDL, no frontend change.

Wires "rerank": "rerank" into conf/models/vllm.json url_suffix so the
existing baseURL join used by Embed/ListModels reaches /v1/rerank.

Adds vllm_rerank_test.go covering happy path, top_n clamp, empty
documents, missing model name, optional-API-key (vLLM-specific),
HTTP error propagation, and out-of-range index rejection.
JinHai-CN pushed a commit that referenced this pull request May 15, 2026
### What problem does this PR solve?

Closes #14878.

`VllmModel.Rerank()` in
[internal/entity/models/vllm.go:551](internal/entity/models/vllm.go#L551)
is currently a stub returning `nil, fmt.Errorf("%s, Rerank not
implemented", z.Name())`, and
[conf/models/vllm.json](conf/models/vllm.json) is missing a `rerank`
entry in `url_suffix`. Chat (long-standing) and embeddings (#14688)
already work, so rerank is the last missing leg of the retrieval
pipeline for operators running everything on a single self-hosted vLLM
server — today they have to point rerank at a different provider, which
defeats the point of a fully local deployment.

Upstream vLLM has supported a Jina/Cohere-compatible `POST /v1/rerank`
endpoint since v0.7
([vllm-project/vllm#12376](vllm-project/vllm#12376)).
The request/response shape is essentially identical to the NVIDIA driver
landed in #14778, so this PR mirrors that structure with two
vLLM-specific adjustments.

This PR replaces the stub with a real implementation against vLLM's
`/v1/rerank`:

- `POST {baseURL}/rerank`
- Request body: `{"model": "<modelName>", "query": "<query>",
"documents": [...], "top_n": <int>}` — documents are a flat `[]string`,
**not** wrapped as `{text: "..."}` like NVIDIA's `/ranking`.
- Response body: `{"results": [{"index": int, "relevance_score": float},
...]}` (Jina-compatible; the optional `document` field is ignored since
callers reconstruct text via `Index`).
- `Authorization: Bearer <ApiKey>` is set **only when `APIConfig.ApiKey`
is non-empty**, matching the existing `Embed`/`ListModels` behaviour in
this file. vLLM is a local driver and can be deployed without an API
key.

The return shape matches the existing `*RerankResponse` contract used by
the NVIDIA ([nvidia.go:461](internal/entity/models/nvidia.go#L461)),
Aliyun ([aliyun.go:507](internal/entity/models/aliyun.go#L507)), and
ZhipuAI ([zhipu-ai.go:554](internal/entity/models/zhipu-ai.go#L554))
drivers, i.e. `Data []RerankResult` carrying `{Index, RelevanceScore}`
in the API's ranking order. Callers that need original-input order sort
by `Index`.

Behaviour requirements from the issue, all covered:

1. Empty `documents` → returns `&RerankResponse{}` without an HTTP call.
2. Missing `modelName` → `"model name is required"` validation error.
3. `rerankConfig.TopN` honored when `0 < TopN < len(documents)`;
otherwise `top_n` defaults to `len(documents)` so callers get a score
per input.
4. Non-200 responses return an error including upstream status and body
(`"vLLM rerank API error: <status>, body: <body>"`).
5. Response `index` values are bounds-checked against `len(documents)`.

**Scope:**

- [internal/entity/models/vllm.go](internal/entity/models/vllm.go) —
replaces the `Rerank` stub at line 551 with a real implementation; adds
`vllmRerankRequest`/`vllmRerankResponse` types for the slim subset of
the payload we need. Region/baseURL resolution, 30s context timeout,
conditional bearer header, and error wrapping all follow the existing
patterns in this file.
- [conf/models/vllm.json](conf/models/vllm.json) — adds `"rerank":
"rerank"` to `url_suffix`, joined to the operator-configured vLLM base
URL the same way the NVIDIA driver joins at
[nvidia.go:485](internal/entity/models/nvidia.go#L485).
-
[internal/entity/models/vllm_rerank_test.go](internal/entity/models/vllm_rerank_test.go)
— adds 7 `httptest`-backed tests mirroring `nvidia_rerank_test.go`:
happy path (out-of-order ranking → Index preservation), `top_n` clamp to
`RerankConfig.TopN`, empty-documents short-circuit, missing-model-name
validation, HTTP error propagation, out-of-range index rejection, and a
vLLM-specific `TestVllmRerankWithoutAPIKey` locking in the optional-auth
behaviour that distinguishes this driver from NVIDIA.

**Out of scope:** no interface change, no DDL, no frontend change. Chat,
embeddings, and balance paths are untouched. No new user-facing docs
required beyond the existing rerank model setup page — vLLM joins the
list of providers whose rerank model can be selected once `/v1/rerank`
is exposed by the server.

### Type of change

- [x] New Feature (non-breaking change which adds functionality)
JinHai-CN pushed a commit that referenced this pull request May 21, 2026
### What problem does this PR solve?

Fixes #14816

The Xinference Go driver landed chat in #14938 and Embed is in review in
#14932, but `Rerank` shipped as a stub that returns `"xinference, no
such method"`. Tenants who launch a rerank model with `--model-type
rerank` on their Xinference instance cannot route it through the Go API
server. This PR fills the gap.

Xinference exposes an OpenAI-compatible REST API. The rerank endpoint is
at `POST <base>/v1/rerank` and accepts the Cohere-shaped body `{model,
query, documents, top_n}`, returning `{results: [{index,
relevance_score}]}` — the same wire shape used by the merged NVIDIA
(#14778), Aliyun (#14676), Gitee (#14656), ZhipuAI (#14608), Novita
(#15014), and LocalAI (#14813) Rerank implementations. Documented in
[Xinference rerank
docs](https://inference.readthedocs.io/en/v1.6.1/models/model_abilities/rerank.html);
the [builtin rerank model
catalog](https://inference.readthedocs.io/en/stable/models/builtin/rerank/)
lists `bge-reranker-base`, `bge-reranker-large`, `bge-reranker-v2-m3`,
and others.
Ricardo-M-L pushed a commit to Ricardo-M-L/ragflow that referenced this pull request Aug 17, 2026
## Summary

- Replaces the `"no such method"` stub on `NvidiaModel.Rerank`
(`internal/entity/models/nvidia.go`) with a real implementation against
NVIDIA NIM's `/ranking` endpoint.
- Mirrors the existing Python `NvidiaRerank` class at
`rag/llm/rerank_model.py:149-190` for behavior parity: same
`passages`/`query.text`/`logit` payload shape; `top_n` set to
`len(documents)` so every input gets a score returned in original order
(the issue body's spec omitted `top_n`, which would cause silent data
loss).
- Adds the `"rerank": "ranking"` URL suffix and two NIM rerank model
entries (`nvidia/nv-rerankqa-mistral-4b-v3`,
`nvidia/llama-3.2-nv-rerankqa-1b-v2`) to `conf/models/nvidia.json` so
the picker exposes them.
- Follows the same shape as the recently merged Aliyun (infiniflow#14676), Gitee
(infiniflow#14656), and ZhipuAI (infiniflow#14608) Rerank implementations: lowercase
per-driver request/response types, conversion to the project-wide
`RerankResponse{Data: []RerankResult}`, per-call `context.WithTimeout`
of 30s.

Closes infiniflow#14720

## Test plan

- [x] `gofmt -l internal/entity/models/nvidia.go` — clean
- [x] `go vet ./internal/entity/models/...` — no new errors introduced
(the two pre-existing vet errors in `baidu.go:642` and
`openrouter.go:566` are unrelated to this PR)
- [x] `go build ./internal/entity/models/...` — succeeds
- [x] `python3 -c "import json;
json.load(open('conf/models/nvidia.json'))"` — JSON valid
- [ ] Live smoke test against NVIDIA NIM with a real API key (requires
reviewer with NIM credentials)

## Notes for reviewers

- The issue body suggested omitting `top_n`. The Python reference
includes it (`top_n: len(texts)`), and without it NVIDIA returns only
the default top-K rankings rather than scores for every input. This PR
follows the Python.
- The URL host is `integrate.api.nvidia.com` (kept consistent with the
existing chat/embeddings BaseURL in `nvidia.go`), not the legacy
`ai.api.nvidia.com` host the Python uses. NIM's unified endpoint accepts
the model names as-is, so no per-model URL transform is needed.
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 Rerank in the NVIDIA Go driver

2 participants