Repository navigation
Go: implement Rerank in Gitee AI driver - #14656
Conversation
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
|
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! |
📝 WalkthroughWalkthroughThis PR implements rerank support for the Gitee AI provider. A new model configuration entry registers ChangesGitee Rerank Feature
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes 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.
Actionable comments posted: 1
🧹 Nitpick comments (1)
internal/entity/models/gitee.go (1)
440-450: ⚡ Quick winURL 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 indexz.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 appliesstrings.TrimSuffix(baseURL, "/")that no other method applies, so a trailing slash on the configured URL would produce double-slash URLs everywhere exceptRerank.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
📒 Files selected for processing (2)
conf/models/gitee.jsoninternal/entity/models/gitee.go
| 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 | ||
| } |
There was a problem hiding this comment.
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.
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
### 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
### 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)
## 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.
### 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.
### 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
### 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)
## 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.
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
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
URL from `BaseURL[region] + URLSuffix.Rerank`.
recently merged Aliyun Encode and the OpenAI driver already use.
output order matches the input order even if the API returns items in a different order.
Type of change
How was this tested?
Closes #14655