Skip to content

Go: implement Rerank in Aliyun driver - #14676

Merged
JinHai-CN merged 5 commits into
infiniflow:mainfrom
Joseff531:go-aliyun-rerank
May 8, 2026
Merged

JinHai-CN merged 5 commits into
infiniflow:mainfrom
Joseff531:go-aliyun-rerank

Conversation

@Joseff531

@Joseff531 Joseff531 commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

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 #14675

Type of change

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

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

coderabbitai Bot commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds Aliyun rerank support: config adds a rerank URL suffix and qwen3-rerank model; Go driver adds rerank request/response types and a full AliyunModel.Rerank implementation. Two stray numeric literals were accidentally inserted and will break Go compilation.

Changes

Aliyun Rerank Support

Layer / File(s) Summary
Configuration Schema
conf/models/aliyun.json
Adds url_suffix.rerank: "compatible-api/v1/reranks" and registers a qwen3-rerank model with max_tokens: 8192 and model_types: ["rerank"].
Rerank Request/Response Types
internal/entity/models/aliyun.go
Adds unexported aliyunRerankRequest and aliyunRerankResponse structs modeling the JSON payload and response.
Rerank Implementation
internal/entity/models/aliyun.go
Implements AliyunModel.Rerank: validates inputs and apiKey, chooses region-specific base URL, POSTs to /compatible-api/v1/reranks, parses results (index + relevance_score), enforces index bounds and duplicate checks, verifies result count equals len(texts), and returns []float64 aligned to input texts.
Syntax Noise (compile error)
internal/entity/models/aliyun.go
Two stray standalone numeric literals (458, 459) were inserted into the file, creating invalid Go tokens that will cause build failures.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • infiniflow/ragflow#14656: Implements a driver-specific Rerank and updates conf/models similarly (related pattern).
  • infiniflow/ragflow#14215: Adds/adjusts handling for qwen3-rerank model and related call arg handling.
  • infiniflow/ragflow#14647: Recent Aliyun driver changes (Encode implementation) that touch similar files and introduced comparable stray numeric-literal artifacts.

Poem

🐰 I hopped through configs, tidy and bright,
Added rerank paths to set things right.
I posted queries, fetched each score,
But two loose numbers tripped the floor.
A nibble, a patch — build runs once more.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning All changes are directly scoped to implementing Rerank functionality: aliyun.json adds rerank configuration, and aliyun.go implements the Rerank method. However, stray numeric literals (458, 459) were inserted in the Encode method outside the PR's stated scope. Remove the stray numeric literals (458, 459) inserted after the embedding encoding logic in the Encode method, as they are not part of the Rerank implementation scope.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: implementing the Rerank method in the Aliyun Go driver.
Linked Issues check ✅ Passed The PR implements all coding requirements from issue #14675: replaces the stub Rerank method with functional DashScope endpoint calls [#14675], adds rerank URL suffix and model entries to the configuration [#14675], validates responses, and returns aligned scores [#14675].
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Description check ✅ Passed PR description addresses the problem, provides context about DashScope's rerank endpoint and existing models, and correctly identifies the change as a new feature.

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

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

517-520: ⚡ Quick win

Add a per-request context with timeout, consistent with Encode.

Encode uses http.NewRequestWithContext with a 30-second deadline. Rerank uses plain http.NewRequest, relying solely on the shared httpClient 120-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

📥 Commits

Reviewing files that changed from the base of the PR and between 94f82ac and aa92aaa.

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

Comment thread internal/entity/models/aliyun.go Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/entity/models/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

📥 Commits

Reviewing files that changed from the base of the PR and between aa92aaa and 500e148.

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

Comment thread internal/entity/models/aliyun.go Resolved
@Joseff531

Copy link
Copy Markdown
Contributor Author

Hi @Magicbook1108,

Sorry for requesting a review from you unexpectedly.
Could you please review the PR when you have a chance?

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:M This PR changes 30-99 lines, ignoring generated files. labels May 8, 2026
Joseff531 added a commit to Joseff531/ragflow that referenced this pull request May 8, 2026

@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 @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.

Comment thread conf/models/aliyun.json Resolved
Comment thread conf/models/aliyun.json Resolved
Comment thread internal/entity/models/aliyun.go Resolved
@Joseff531
Joseff531 requested a review from Haruko386 May 8, 2026 10:21

@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)
conf/models/aliyun.json (1)

36-42: 💤 Low value

Consider adding gte-rerank-v2 / qwen3-vl-rerank in a follow-up.

qwen3-rerank is correctly paired with the compatible-api/v1/reranks suffix. 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 the url_suffix schema 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-v2 and qwen3-vl-rerank once 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

📥 Commits

Reviewing files that changed from the base of the PR and between 9d68d77 and 1a6fcc4.

📒 Files selected for processing (1)
  • conf/models/aliyun.json

@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.

@Joseff531 LGTM

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

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.
📢 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 2ad854c into infiniflow:main May 8, 2026
2 checks passed
@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.
@coderabbitai coderabbitai Bot mentioned this pull request May 12, 2026
1 task done
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 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)
Ricardo-M-L pushed a commit to Ricardo-M-L/ragflow that referenced this pull request Aug 17, 2026
## Summary

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

Closes infiniflow#14720

## Test plan

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

## Notes for reviewers

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

Labels

ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

3 participants