Skip to content

Go: implement Rerank in ZhipuAI driver - #14608

Merged
JinHai-CN merged 1 commit into
infiniflow:mainfrom
pandadev66:feat/go-zhipu-rerank
May 7, 2026
Merged

JinHai-CN merged 1 commit into
infiniflow:mainfrom
pandadev66:feat/go-zhipu-rerank

Conversation

@pandadev66

@pandadev66 pandadev66 commented May 7, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

The ZhipuAI Go driver had a stub Rerank method that returned "not implemented", even though conf/models/zhipu-ai.json already ships glm-rerank as a rerank model and the rerank URL suffix is already wired in url_suffix:

"url_suffix": {
  ...
  "rerank": "rerank"
},
"models": [
  {"name": "glm-rerank", "model_types": ["rerank"]},
  ...
]

So the config was ready but the driver was not. A tenant who picked glm-rerank in the Go layer could not actually run a rerank call. This PR fills the gap so the listed model works end to end.

What this PR includes

  • internal/entity/models/zhipu-ai.go: real implementation of ZhipuAIModel.Rerank, plus two small local types (zhipuRerankRequest, zhipuRerankResponse) that mirror the standard OpenAI-compatible rerank shape used by SiliconFlow.

No factory change. No JSON change. No interface change.

How the driver works

  • POST to ${BaseURL}/${URLSuffix.Rerank} (resolves to https://open.bigmodel.cn/api/paas/v4/rerank with the default config), reusing the existing httpClient on the driver.
  • Validate apiConfig and the API key, validate the model name, and resolve the region. Return a clear local error before any HTTP call when something is missing.
  • Send {model, query, documents, top_n, return_documents: false} in the body, the same shape the SiliconFlow driver already uses.
  • Walk results[*].relevance_score and copy each score into the output slice indexed by results[*].index, so the output order matches the input order even if the API returns results in a different order.
  • Empty texts input returns an empty []float64 with no HTTP call.
  • Non-200 responses propagate the upstream status line and body.

Type of change

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

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 ZhipuAIModel still matches the ModelDriver interface (NewInstance, Name, ChatWithMessages, ChatStreamlyWithSender, Encode, ListModels, Balance, CheckConnection, Rerank).
  • Pattern parity with the existing SiliconFlow Rerank implementation (internal/entity/models/siliconflow.go).

Closes #14607

The ZhipuAI Go driver had a stub Rerank method that returned
"not implemented", even though conf/models/zhipu-ai.json already
ships glm-rerank as a rerank model and the rerank URL suffix is
already wired in url_suffix.

A tenant who picked glm-rerank in the Go layer could not actually
run a rerank call. This commit adds the real implementation so
the listed model works end to end.

How it works:

- POST to ${BaseURL}/${URLSuffix.Rerank} (resolves to
  https://open.bigmodel.cn/api/paas/v4/rerank with the default
  config) using the existing httpClient on the driver.
- Validate apiConfig and the API key, validate the model name,
  and resolve the region. Return a clear local error before any
  HTTP call when something is missing.
- Send {model, query, documents, top_n, return_documents:false}
  in the body, the same OpenAI-compatible shape the SiliconFlow
  driver already uses for its rerank call.
- Walk results[*].relevance_score and copy each score into the
  output slice indexed by results[*].index, so the output order
  matches the input order even if the API returns results in a
  different order.

Empty texts input returns an empty []float64 with no HTTP call.
Non-200 responses propagate the upstream status line and body.

Closes infiniflow#14607
@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label May 7, 2026
@pandadev66

Copy link
Copy Markdown
Contributor Author

Hi @Magicbook1108, gentle ping for review. This follows the same pattern as the existing SiliconFlow Rerank, scope is one file, and it closes #14607. Thanks!

@coderabbitai

coderabbitai Bot commented May 7, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

The PR implements the Rerank method in the ZhipuAI Go driver, replacing a stub with a full implementation that validates inputs, calls the ZhipuAI /rerank endpoint, and returns per-text relevance scores. A code corruption issue in CheckConnection is also fixed.

Changes

ZhipuAI Rerank Implementation

Layer / File(s) Summary
Code Fix
internal/entity/models/zhipu-ai.go (lines 489–491)
Removed stray numeric text that corrupted the CheckConnection function, restoring valid Go syntax.
Data Shape
internal/entity/models/zhipu-ai.go (lines 492–511)
Added zhipuRerankRequest and zhipuRerankResponse types to define the JSON payload shape for the ZhipuAI rerank endpoint.
Core Implementation
internal/entity/models/zhipu-ai.go (lines 515–588)
Implemented the Rerank method with input validation, region-based URL selection, HTTP POST to /rerank, response parsing, and score-array generation aligned to input text order.

Sequence Diagram

sequenceDiagram
    participant Client as Caller
    participant ZhipuAI as ZhipuAIModel
    participant HTTP as HTTP Client
    participant Endpoint as ZhipuAI Service

    Client->>ZhipuAI: Rerank(modelName, query, texts[], apiConfig)
    ZhipuAI->>ZhipuAI: Validate inputs & select base URL by region
    ZhipuAI->>ZhipuAI: Build zhipuRerankRequest payload
    ZhipuAI->>HTTP: POST /api/paas/v4/rerank<br/>(with Bearer auth)
    HTTP->>Endpoint: Send rerank request
    Endpoint-->>HTTP: Return JSON response
    HTTP-->>ZhipuAI: HTTP status + body
    ZhipuAI->>ZhipuAI: Parse zhipuRerankResponse
    ZhipuAI->>ZhipuAI: Extract & align scores to input order
    ZhipuAI-->>Client: Return []float64 scores
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Poem

🐰 A rerank is born, no longer stuck,
ZhipuAI scores texts with just one pluck,
HTTP posts dance to /rerank's call,
Relevance scores align for all,
glm-rerank hops where it could not before!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically summarizes the main change: implementing the Rerank method in the ZhipuAI driver.
Description check ✅ Passed The PR description is comprehensive, covering the problem, solution, implementation details, testing approach, and the affected file, matching the template with the 'New Feature' type selected.
Linked Issues check ✅ Passed The PR fully implements all coding objectives from #14607: Rerank method implementation with OpenAI-compatible request/response shapes, POST to /api/paas/v4/rerank endpoint, input validation, per-call context, and proper score ordering.
Out of Scope Changes check ✅ Passed All changes are scoped to internal/entity/models/zhipu-ai.go and directly address the Rerank implementation requirement with no unrelated modifications.
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.

@Magicbook1108
Magicbook1108 requested a review from Haruko386 May 7, 2026 02:26

@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/zhipu-ai.go (1)

553-565: ⚡ Quick win

Per-call context deadline is missing despite being stated as an objective.

PR objectives call out: "Use a per-call context deadline to avoid blocking", but this implementation uses http.NewRequest (no context) and relies solely on z.httpClient.Timeout (120s) as a backstop. That timeout is a global setting on the shared client and is not per-call cancellable. Consider http.NewRequestWithContext with a context.WithTimeout so callers/tests get proper cancellation semantics and the deadline is explicit at this call site.

♻️ Suggested change
@@
 import (
 	"bufio"
 	"bytes"
+	"context"
 	"encoding/json"
 	"fmt"
 	"io"
 	"net/http"
 	"ragflow/internal/common"
 	"strings"
 	"time"
 )
@@
-	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
-	if err != nil {
-		return nil, fmt.Errorf("failed to create request: %w", err)
-	}
+	ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
+	defer cancel()
+	req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(jsonData))
+	if err != nil {
+		return nil, fmt.Errorf("failed to create request: %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/entity/models/zhipu-ai.go` around lines 553 - 565, The request
currently uses http.NewRequest and relies on z.httpClient.Timeout; replace this
with a per-call cancellable context by creating a ctx, cancel :=
context.WithTimeout(parentCtxOrBackground, desiredTimeout) and use
http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(jsonData)); call
defer cancel() after creation and then use z.httpClient.Do(req) as before so the
call is cancellable independently of the shared client's Timeout; ensure you
keep resp.Body.Close() handling and include the same headers (e.g.,
Authorization with *apiConfig.ApiKey).
🤖 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/zhipu-ai.go`:
- Around line 553-565: The request currently uses http.NewRequest and relies on
z.httpClient.Timeout; replace this with a per-call cancellable context by
creating a ctx, cancel := context.WithTimeout(parentCtxOrBackground,
desiredTimeout) and use http.NewRequestWithContext(ctx, "POST", url,
bytes.NewBuffer(jsonData)); call defer cancel() after creation and then use
z.httpClient.Do(req) as before so the call is cancellable independently of the
shared client's Timeout; ensure you keep resp.Body.Close() handling and include
the same headers (e.g., Authorization with *apiConfig.ApiKey).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 147f054c-356a-436d-9322-f2144f2d0f64

📥 Commits

Reviewing files that changed from the base of the PR and between 1d0519d and 0970ff2.

📒 Files selected for processing (1)
  • internal/entity/models/zhipu-ai.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 @pandadev66, LGTM

Thanks for the contribution. I have reviewed the implementation of the Zhipu AI Rerank endpoint. The core logic successfully mirrors our existing standard API.

While the code structure is highly robust, we may need to conduct further integration testing in the future to fully verify its overall feasibility and stability in RAGflows.

@JinHai-CN JinHai-CN added the ci Continue Integration label May 7, 2026
@JinHai-CN
JinHai-CN marked this pull request as draft May 7, 2026 06:19
@JinHai-CN
JinHai-CN marked this pull request as ready for review May 7, 2026 06:19
@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 (1d0519d) to head (0970ff2).
⚠️ Report is 6 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14608   +/-   ##
=======================================
  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 bb10b83 into infiniflow:main May 7, 2026
1 check passed
JinHai-CN pushed a commit that referenced this pull request May 8, 2026
### What problem does this PR solve?

The Gitee AI Go driver shipped with a stub \`Rerank\` method that
returned \`Rerank not implemented\`, even though
\`conf/models/gitee.json\` already wires the rerank URL suffix at
\`\"rerank\": \"rerank\"\`. The same config did not list any
rerank model, so the picker had nothing to select.

So a Gitee tenant could not use BAAI/bge-reranker-v2-m3 as a reranker
through the Go layer today, even though the
infrastructure was one config entry and one method body away.

### What this PR includes

- \`conf/models/gitee.json\`: add \`BAAI/bge-reranker-v2-m3\` to the
\`models\` array.
- \`internal/entity/models/gitee.go\`: replace the \`Rerank\` stub with
a real implementation. Adds two small local types
that match the OpenAI-compatible \`/rerank\` shape already used by the
SiliconFlow and ZhipuAI drivers.

No factory change. No interface change.

### How the driver works

- Validate \`apiConfig\` and the API key, validate the model name,
resolve the region with a default fallback, build the
  URL from \`BaseURL[region] + URLSuffix.Rerank\`.
- Use a per-call \`context.WithTimeout(30s)\` and
\`http.NewRequestWithContext\`, matching the pattern the
  recently merged Aliyun Encode and the OpenAI driver already use.
- Send \`{model, query, documents, top_n, return_documents:false}\` in
the body.
- Parse \`results[*].relevance_score\` and copy each score into the
output slice indexed by \`results[*].index\`, so the
output order matches the input order even if the API returns items in a
different order.
- Empty input returns \`[]float64{}\` with no HTTP call.
- An out-of-range result index returns a clear error rather than
silently skipping the entry.
- Non-200 responses propagate the upstream status line and body.

### Type of change

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

### How was this tested?

- \`go build ./internal/entity/models/...\` in a clean go 1.25 image
returns exit 0.
- The full method set on \`GiteeModel\` still matches the
\`ModelDriver\` interface.
- Pattern parity with the existing SiliconFlow Rerank and the recently
merged ZhipuAI Rerank (#14608).

Closes #14655
pekar9781 pushed a commit to pekar9781/ragflow that referenced this pull request May 8, 2026
### What problem does this PR solve?

The Gitee AI Go driver shipped with a stub \`Rerank\` method that
returned \`Rerank not implemented\`, even though
\`conf/models/gitee.json\` already wires the rerank URL suffix at
\`\"rerank\": \"rerank\"\`. The same config did not list any
rerank model, so the picker had nothing to select.

So a Gitee tenant could not use BAAI/bge-reranker-v2-m3 as a reranker
through the Go layer today, even though the
infrastructure was one config entry and one method body away.

### What this PR includes

- \`conf/models/gitee.json\`: add \`BAAI/bge-reranker-v2-m3\` to the
\`models\` array.
- \`internal/entity/models/gitee.go\`: replace the \`Rerank\` stub with
a real implementation. Adds two small local types
that match the OpenAI-compatible \`/rerank\` shape already used by the
SiliconFlow and ZhipuAI drivers.

No factory change. No interface change.

### How the driver works

- Validate \`apiConfig\` and the API key, validate the model name,
resolve the region with a default fallback, build the
  URL from \`BaseURL[region] + URLSuffix.Rerank\`.
- Use a per-call \`context.WithTimeout(30s)\` and
\`http.NewRequestWithContext\`, matching the pattern the
  recently merged Aliyun Encode and the OpenAI driver already use.
- Send \`{model, query, documents, top_n, return_documents:false}\` in
the body.
- Parse \`results[*].relevance_score\` and copy each score into the
output slice indexed by \`results[*].index\`, so the
output order matches the input order even if the API returns items in a
different order.
- Empty input returns \`[]float64{}\` with no HTTP call.
- An out-of-range result index returns a clear error rather than
silently skipping the entry.
- Non-200 responses propagate the upstream status line and body.

### Type of change

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

### How was this tested?

- \`go build ./internal/entity/models/...\` in a clean go 1.25 image
returns exit 0.
- The full method set on \`GiteeModel\` still matches the
\`ModelDriver\` interface.
- Pattern parity with the existing SiliconFlow Rerank and the recently
merged ZhipuAI Rerank (infiniflow#14608).

Closes infiniflow#14655
@coderabbitai coderabbitai Bot mentioned this pull request May 9, 2026
1 task done
@ai-mountain ai-mountain mentioned this pull request May 11, 2026
4 of 5 tasks
JinHai-CN pushed a commit that referenced this pull request May 11, 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 (#14676), Gitee
(#14656), and ZhipuAI (#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

- [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.
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
### What problem does this PR solve?

The ZhipuAI Go driver had a stub Rerank method that returned "not
implemented", even though conf/models/zhipu-ai.json already ships
glm-rerank as a rerank model and the rerank URL suffix is already wired
in url_suffix:

```json
"url_suffix": {
  ...
  "rerank": "rerank"
},
"models": [
  {"name": "glm-rerank", "model_types": ["rerank"]},
  ...
]
```

So the config was ready but the driver was not. A tenant who picked
glm-rerank in the Go layer could not actually run a rerank call. This PR
fills the gap so the listed model works end to end.

### What this PR includes

- `internal/entity/models/zhipu-ai.go`: real implementation of
`ZhipuAIModel.Rerank`, plus two small local types (`zhipuRerankRequest`,
`zhipuRerankResponse`) that mirror the standard OpenAI-compatible rerank
shape used by SiliconFlow.

No factory change. No JSON change. No interface change.

### How the driver works

- POST to `${BaseURL}/${URLSuffix.Rerank}` (resolves to
`https://open.bigmodel.cn/api/paas/v4/rerank` with the default config),
reusing the existing httpClient on the driver.
- Validate apiConfig and the API key, validate the model name, and
resolve the region. Return a clear local error before any HTTP call when
something is missing.
- Send `{model, query, documents, top_n, return_documents: false}` in
the body, the same shape the SiliconFlow driver already uses.
- Walk `results[*].relevance_score` and copy each score into the output
slice indexed by `results[*].index`, so the output order matches the
input order even if the API returns results in a different order.
- Empty `texts` input returns an empty `[]float64` with no HTTP call.
- Non-200 responses propagate the upstream status line and body.

### Type of change

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

### 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 `ZhipuAIModel` still matches the `ModelDriver`
interface (NewInstance, Name, ChatWithMessages, ChatStreamlyWithSender,
Encode, ListModels, Balance, CheckConnection, Rerank).
- Pattern parity with the existing SiliconFlow Rerank implementation
(`internal/entity/models/siliconflow.go`).

Closes infiniflow#14607
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 Gitee AI Go driver shipped with a stub \`Rerank\` method that
returned \`Rerank not implemented\`, even though
\`conf/models/gitee.json\` already wires the rerank URL suffix at
\`\"rerank\": \"rerank\"\`. The same config did not list any
rerank model, so the picker had nothing to select.

So a Gitee tenant could not use BAAI/bge-reranker-v2-m3 as a reranker
through the Go layer today, even though the
infrastructure was one config entry and one method body away.

### What this PR includes

- \`conf/models/gitee.json\`: add \`BAAI/bge-reranker-v2-m3\` to the
\`models\` array.
- \`internal/entity/models/gitee.go\`: replace the \`Rerank\` stub with
a real implementation. Adds two small local types
that match the OpenAI-compatible \`/rerank\` shape already used by the
SiliconFlow and ZhipuAI drivers.

No factory change. No interface change.

### How the driver works

- Validate \`apiConfig\` and the API key, validate the model name,
resolve the region with a default fallback, build the
  URL from \`BaseURL[region] + URLSuffix.Rerank\`.
- Use a per-call \`context.WithTimeout(30s)\` and
\`http.NewRequestWithContext\`, matching the pattern the
  recently merged Aliyun Encode and the OpenAI driver already use.
- Send \`{model, query, documents, top_n, return_documents:false}\` in
the body.
- Parse \`results[*].relevance_score\` and copy each score into the
output slice indexed by \`results[*].index\`, so the
output order matches the input order even if the API returns items in a
different order.
- Empty input returns \`[]float64{}\` with no HTTP call.
- An out-of-range result index returns a clear error rather than
silently skipping the entry.
- Non-200 responses propagate the upstream status line and body.

### Type of change

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

### How was this tested?

- \`go build ./internal/entity/models/...\` in a clean go 1.25 image
returns exit 0.
- The full method set on \`GiteeModel\` still matches the
\`ModelDriver\` interface.
- Pattern parity with the existing SiliconFlow Rerank and the recently
merged ZhipuAI Rerank (infiniflow#14608).

Closes infiniflow#14655
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:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature Request]: Implement Rerank in the ZhipuAI Go driver

3 participants