Repository navigation
Go: implement Rerank in Aliyun driver - #14676
Conversation
📝 WalkthroughWalkthroughAdds Aliyun rerank support: config adds a rerank URL suffix and ChangesAliyun Rerank Support
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 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/aliyun.go (1)
517-520: ⚡ Quick winAdd a per-request context with timeout, consistent with
Encode.
Encodeuseshttp.NewRequestWithContextwith a 30-second deadline.Rerankuses plainhttp.NewRequest, relying solely on the sharedhttpClient120-second transport timeout with no per-request cancellation.♻️ Proposed fix
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + - req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) + 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/aliyun.go` around lines 517 - 520, The Rerank function currently uses http.NewRequest without a per-request context; update Rerank to mirror Encode by creating a context with a 30-second timeout (context.WithTimeout) and call http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(jsonData)), ensure you defer cancel() to avoid leaks, and propagate that request to the existing httpClient so the request is cancellable per-request.
🤖 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/aliyun.go`:
- Around line 545-550: The loop that fills scores from rerankResp.Results can
silently leave zeros when an index is missing or out of range; update the
reranking code (the block that constructs scores from rerankResp.Results) to
validate results: check that len(rerankResp.Results) == len(texts) and that each
r.Index is within [0,len(texts)), and if not either return an error (matching
Encode's behavior) or at minimum emit a clear warning including the offending
r.Index and lengths; ensure you reference the same variables
(rerankResp.Results, texts, scores) so the function fails fast instead of
silently leaving zero scores.
---
Nitpick comments:
In `@internal/entity/models/aliyun.go`:
- Around line 517-520: The Rerank function currently uses http.NewRequest
without a per-request context; update Rerank to mirror Encode by creating a
context with a 30-second timeout (context.WithTimeout) and call
http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(jsonData)), ensure
you defer cancel() to avoid leaks, and propagate that request to the existing
httpClient so the request is cancellable per-request.
🪄 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: 136e4065-174a-4e81-9a52-725647c0d195
📒 Files selected for processing (2)
conf/models/aliyun.jsoninternal/entity/models/aliyun.go
There was a problem hiding this comment.
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/aliyun.go`:
- Around line 545-556: The current rerank result handling in aliyun.go can miss
duplicate or missing indices; update the block that iterates over
rerankResp.Results (the loop filling scores := make([]float64, len(texts))) to
validate index uniqueness and full coverage: create a seen boolean slice or map
sized to len(texts), for each result check r.Index is in range and not already
seen (return an error for out-of-range or duplicate indices), mark
seen[r.Index]=true and set scores[r.Index]=r.RelevanceScore, then after the loop
verify every index was seen (return an error if any index is missing) instead of
only comparing lengths. Ensure error messages reference the specific r.Index and
expected range for easier debugging.
🪄 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: d5b7fcf6-6699-49ff-b8fd-74d8e80aa09c
📒 Files selected for processing (1)
internal/entity/models/aliyun.go
|
Hi @Magicbook1108, Sorry for requesting a review from you unexpectedly. |
Haruko386
left a comment
There was a problem hiding this comment.
Hi @Joseff531 , I noticed there is a mismatch between the documented response schema and the implementation here.
The JSON example in the docs/config appears to follow the gte-rerank-v2 response format, where the rerank results are wrapped differently, while the actual Go parsing logic is implemented according to the qwen3-rerank response schema:
{
"object": "list",
"results": [...]
}
However, the code currently assumes the qwen3-rerank structure directly when unmarshalling the response.
I suggest keeping only qwen3-rerank; please read the documentation carefully before making any changes.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
conf/models/aliyun.json (1)
36-42: 💤 Low valueConsider adding
gte-rerank-v2/qwen3-vl-rerankin a follow-up.
qwen3-rerankis correctly paired with thecompatible-api/v1/rerankssuffix. However, other Aliyun rerankers (gte-rerank-v2,qwen3-vl-rerank) use a different endpoint (api/v1/services/rerank/text-rerank/text-rerank), which means they cannot be registered here without extending theurl_suffixschema to support multiple rerank paths. Worth tracking as a follow-up once the driver supports routing by model type or name.Want me to open a follow-up issue to track supporting
gte-rerank-v2andqwen3-vl-rerankonce the driver can handle per-model URL routing?🤖 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 `@conf/models/aliyun.json` around lines 36 - 42, Add a follow-up to support Aliyun rerank variants that use a different endpoint by tracking models "gte-rerank-v2" and "qwen3-vl-rerank" and updating the URL routing schema: extend the existing url_suffix handling (currently using "compatible-api/v1/reranks") to allow multiple rerank endpoints (including "api/v1/services/rerank/text-rerank/text-rerank") or per-model routing, and create an issue referencing the models "qwen3-rerank", "gte-rerank-v2", and "qwen3-vl-rerank" so this work can be implemented once the driver supports routing by model type/name.
🤖 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 `@conf/models/aliyun.json`:
- Around line 36-42: Add a follow-up to support Aliyun rerank variants that use
a different endpoint by tracking models "gte-rerank-v2" and "qwen3-vl-rerank"
and updating the URL routing schema: extend the existing url_suffix handling
(currently using "compatible-api/v1/reranks") to allow multiple rerank endpoints
(including "api/v1/services/rerank/text-rerank/text-rerank") or per-model
routing, and create an issue referencing the models "qwen3-rerank",
"gte-rerank-v2", and "qwen3-vl-rerank" so this work can be implemented once the
driver supports routing by model type/name.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 8f8291b2-f77b-4d00-a193-c701633afb49
📒 Files selected for processing (1)
conf/models/aliyun.json
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14676 +/- ##
=======================================
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:
|
## 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 Aliyun Go driver has a stub `Rerank` method that always returns `"Aliyun, Rerank not implemented"`. DashScope exposes an OpenAI-compatible rerank endpoint (`compatible-mode/v1/rerank`) and hosts dedicated bilingual rerankers (`gte-rerank-v2`, `gte-rerank`) that are a natural pairing with the embedding models already in `aliyun.json`. Without this, Aliyun users cannot use reranking within RAGFlow. Closes infiniflow#14675 ### 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 Aliyun Go driver has a stub
Rerankmethod that always returns"Aliyun, Rerank not implemented". DashScope exposes an OpenAI-compatible rerank endpoint (compatible-mode/v1/rerank) and hosts dedicated bilingual rerankers (gte-rerank-v2,gte-rerank) that are a natural pairing with the embedding models already inaliyun.json. Without this, Aliyun users cannot use reranking within RAGFlow.Closes #14675
Type of change