Skip to content

Go: implement Rerank in Gitee AI driver - #14656

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

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

Conversation

@pandadev66

@pandadev66 pandadev66 commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

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

  • 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 (Go: implement Rerank in ZhipuAI driver #14608).

Closes #14655

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". The same config did not list any rerank model, so
the picker had nothing to select.

Changes:

- conf/models/gitee.json: add the BAAI/bge-reranker-v2-m3
  entry 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 used by SiliconFlow
  and ZhipuAI.

How it 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, the same pattern the recent
  Aliyun Encode uses.
- 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.
- Empty input returns an empty []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.

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

Copy link
Copy Markdown
Contributor Author

Hi @Magicbook1108, gentle ping for review. Same OpenAI-compatible /rerank shape that the merged SiliconFlow Rerank and ZhipuAI Rerank (#14608) already use, scope is two files (one config, one driver), and it closes #14655. Thanks!

@coderabbitai

coderabbitai Bot commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR implements rerank support for the Gitee AI provider. A new model configuration entry registers BAAI/bge-reranker-v2-m3 in gitee.json, and the Go driver now executes real HTTP POST requests to the Gitee rerank endpoint instead of returning a stub "not implemented" error.

Changes

Gitee Rerank Feature

Layer / File(s) Summary
Model Configuration
conf/models/gitee.json
BAAI/bge-reranker-v2-m3 model entry added with max_tokens: 8192 and model_types: ["rerank"].
Rerank Implementation
internal/entity/models/gitee.go
Context import added for timeout support; Rerank method validates inputs, resolves region-specific endpoint, POSTs OpenAI-compatible request body with 30-second deadline, unmarshals response, validates returned indices, and returns score slice aligned to original text order; old stub implementation removed.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Suggested labels

ci

Suggested reviewers

  • Haruko386

Poem

🐰 A reranker hops into Gitee's embrace,
BAAI scores dance at their proper pace,
Context timeouts keep swift the flight,
From stub to real, the feature shines bright! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Go: implement Rerank in Gitee AI driver' directly describes the main change—implementing the Rerank method for the Gitee AI driver.
Description check ✅ Passed The PR description comprehensively covers all required sections: problem statement, included changes, implementation details, type of change, testing approach, and issue closure.
Linked Issues check ✅ Passed The PR fully satisfies all coding requirements from issue #14655: implements GiteeModel.Rerank with proper validation, region resolution, HTTP context timeout, OpenAI-compatible request shape, score mapping, and adds BAAI/bge-reranker-v2-m3 to the model config.
Out of Scope Changes check ✅ Passed All changes are directly scoped to the two files specified in issue #14655: conf/models/gitee.json (adds rerank model) and internal/entity/models/gitee.go (implements Rerank method with supporting types).
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.

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

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

440-450: ⚡ Quick win

URL resolution pattern is inconsistent with the rest of the driver.

Lines 440–445 implement a two-step lookup with a "default" fallback that the other methods (ChatWithMessages, ChatStreamlyWithSender, ListModels, Balance, CheckConnection) don't do — they all index z.BaseURL[region] directly and silently get "" for an unrecognised region. This divergence means a misconfigured non-default region would behave differently across methods. Additionally, line 450 applies strings.TrimSuffix(baseURL, "/") that no other method applies, so a trailing slash on the configured URL would produce double-slash URLs everywhere except Rerank.

Consider extracting a helper used by all methods:

♻️ Proposed refactor
+// resolveBaseURL returns the base URL for the given region, falling back to "default".
+// Returns "" if neither key is present.
+func (z *GiteeModel) resolveBaseURL(region string) string {
+    if url, ok := z.BaseURL[region]; ok && url != "" {
+        return strings.TrimSuffix(url, "/")
+    }
+    return strings.TrimSuffix(z.BaseURL["default"], "/")
+}

Then in Rerank:

-    baseURL := z.BaseURL["default"]
-    if region != "default" {
-        if regional, ok := z.BaseURL[region]; ok && regional != "" {
-            baseURL = regional
-        }
-    }
-    if baseURL == "" {
-        return nil, fmt.Errorf("gitee: no base URL configured for default region")
-    }
-    url := fmt.Sprintf("%s/%s", strings.TrimSuffix(baseURL, "/"), z.URLSuffix.Rerank)
+    baseURL := z.resolveBaseURL(region)
+    if baseURL == "" {
+        return nil, fmt.Errorf("gitee: no base URL configured for region %q", region)
+    }
+    url := fmt.Sprintf("%s/%s", baseURL, z.URLSuffix.Rerank)
🤖 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/gitee.go` around lines 440 - 450, The URL resolution
in Rerank is inconsistent: it falls back to z.BaseURL["default"], trims trailing
slashes with strings.TrimSuffix, and thus behaves differently from other methods
that directly use z.BaseURL[region]; fix by extracting a shared helper (e.g.,
func resolveBaseURL(z *Gitee, region string) (string, error)) that returns
z.BaseURL[region] (or ""/error consistent with other callers) and normalizes
trailing slashes the same way across all callers; update Rerank to call
resolveBaseURL and use its returned base URL when building the final url for
Rerank so region lookup and slash normalization are uniform with
ChatWithMessages, ChatStreamlyWithSender, ListModels, Balance, and
CheckConnection.
🤖 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/gitee.go`:
- Around line 496-502: The code currently silently leaves zero values in scores
when parsed.Results is missing entries; add an explicit guard in the rerank
handling (before populating scores) that checks if len(parsed.Results) !=
len(texts) (or TopN) and returns an error describing the mismatch so callers can
distinguish missing results from a legitimate 0.0 relevance; update the block
that iterates parsed.Results (symbols: parsed.Results, scores, texts) to perform
this length check and fail fast if the API returned fewer results than expected.

---

Nitpick comments:
In `@internal/entity/models/gitee.go`:
- Around line 440-450: The URL resolution in Rerank is inconsistent: it falls
back to z.BaseURL["default"], trims trailing slashes with strings.TrimSuffix,
and thus behaves differently from other methods that directly use
z.BaseURL[region]; fix by extracting a shared helper (e.g., func
resolveBaseURL(z *Gitee, region string) (string, error)) that returns
z.BaseURL[region] (or ""/error consistent with other callers) and normalizes
trailing slashes the same way across all callers; update Rerank to call
resolveBaseURL and use its returned base URL when building the final url for
Rerank so region lookup and slash normalization are uniform with
ChatWithMessages, ChatStreamlyWithSender, ListModels, Balance, and
CheckConnection.
🪄 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: 91e0b1c3-99ec-4656-a0c8-3e43f024be31

📥 Commits

Reviewing files that changed from the base of the PR and between f063e03 and 8f31b38.

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

Comment on lines +496 to +502
scores := make([]float64, len(texts))
for _, r := range parsed.Results {
if r.Index < 0 || r.Index >= len(texts) {
return nil, fmt.Errorf("unexpected rerank index %d for %d inputs", r.Index, len(texts))
}
scores[r.Index] = r.RelevanceScore
}

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 | 🟡 Minor | ⚡ Quick win

Silent zero scores for unscored documents may mask API contract violations.

scores is zero-initialized, so any index not present in parsed.Results silently gets 0.0. Because TopN = len(texts), the API should return all results, but if it ever returns fewer (e.g., an upstream error mid-stream, or API-side deduplication), the caller cannot distinguish a genuine relevance score of 0.0 from a document the API simply skipped. Consider returning an error when len(parsed.Results) != len(texts):

🛡️ Proposed guard
+    if len(parsed.Results) != len(texts) {
+        return nil, fmt.Errorf("gitee rerank: expected %d results, got %d", len(texts), len(parsed.Results))
+    }
     scores := make([]float64, len(texts))
     for _, r := range parsed.Results {
🤖 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/gitee.go` around lines 496 - 502, The code currently
silently leaves zero values in scores when parsed.Results is missing entries;
add an explicit guard in the rerank handling (before populating scores) that
checks if len(parsed.Results) != len(texts) (or TopN) and returns an error
describing the mismatch so callers can distinguish missing results from a
legitimate 0.0 relevance; update the block that iterates parsed.Results
(symbols: parsed.Results, scores, texts) to perform this length check and fail
fast if the API returned fewer results than expected.

@JinHai-CN
JinHai-CN marked this pull request as draft May 8, 2026 04:25
@JinHai-CN
JinHai-CN marked this pull request as ready for review May 8, 2026 04:25
@codecov

codecov Bot commented May 8, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (f063e03) to head (8f31b38).

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

The Gitee AI Go driver in `internal/entity/models/gitee.go` shipped with
a stub `Encode` method that returned `gitee, no such method`, even
though `conf/models/gitee.json` already wires the `embedding` URL
suffix. The conf also listed no embedding models, so the picker had
nothing to select.

This blocked any tenant who wanted to use Gitee AI for chat, rerank
(already working, see #14656), and embeddings from a single provider.

This PR fills the gap, mirroring the just-merged Aliyun `Encode`
(#14647):

- `internal/entity/models/gitee.go`: replace the `Encode` stub with a
real implementation.
Validates inputs, resolves the region with a default fallback, POSTs the
standard OpenAI-compatible `{"model", "input": [...]}` body to
`BaseURL[region] + URLSuffix.Embedding`, parses `data[*].embedding`
indexed by `data[*].index` so output order matches input order, handles
both `float64` and `float32` element types, and uses a 30s per-call
context deadline matching the merged `Rerank`.
- `conf/models/gitee.json`: add `BAAI/bge-m3` so the embedding picker
has something to select.

No factory change. No interface change. No URL suffix change.

Verified with `go build`, `go vet`, and `gofmt -l` : all clean.

Closes #14697

### Type of change

- [x] New Feature (non-breaking change which adds functionality)
@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 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
### What problem does this PR solve?

The Gitee AI Go driver in `internal/entity/models/gitee.go` shipped with
a stub `Encode` method that returned `gitee, no such method`, even
though `conf/models/gitee.json` already wires the `embedding` URL
suffix. The conf also listed no embedding models, so the picker had
nothing to select.

This blocked any tenant who wanted to use Gitee AI for chat, rerank
(already working, see infiniflow#14656), and embeddings from a single provider.

This PR fills the gap, mirroring the just-merged Aliyun `Encode`
(infiniflow#14647):

- `internal/entity/models/gitee.go`: replace the `Encode` stub with a
real implementation.
Validates inputs, resolves the region with a default fallback, POSTs the
standard OpenAI-compatible `{"model", "input": [...]}` body to
`BaseURL[region] + URLSuffix.Embedding`, parses `data[*].embedding`
indexed by `data[*].index` so output order matches input order, handles
both `float64` and `float32` element types, and uses a 30s per-call
context deadline matching the merged `Rerank`.
- `conf/models/gitee.json`: add `BAAI/bge-m3` so the embedding picker
has something to select.

No factory change. No interface change. No URL suffix change.

Verified with `go build`, `go vet`, and `gofmt -l` : all clean.

Closes infiniflow#14697

### Type of change

- [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
## 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 Gitee AI Go driver

2 participants