Skip to content

Go: implement Rerank in vLLM driver (#14878) - #14880

Merged
JinHai-CN merged 1 commit into
infiniflow:mainfrom
hunnyboy1217:feat/go-vllm-rerank
May 15, 2026
Merged

JinHai-CN merged 1 commit into
infiniflow:mainfrom
hunnyboy1217:feat/go-vllm-rerank

Conversation

@hunnyboy1217

@hunnyboy1217 hunnyboy1217 commented May 13, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Closes #14878.

VllmModel.Rerank() in internal/entity/models/vllm.go:551 is currently a stub returning nil, fmt.Errorf("%s, Rerank not implemented", z.Name()), and conf/models/vllm.json is missing a rerank entry in url_suffix. Chat (long-standing) and embeddings (#14688) already work, so rerank is the last missing leg of the retrieval pipeline for operators running everything on a single self-hosted vLLM server — today they have to point rerank at a different provider, which defeats the point of a fully local deployment.

Upstream vLLM has supported a Jina/Cohere-compatible POST /v1/rerank endpoint since v0.7 (vllm-project/vllm#12376). The request/response shape is essentially identical to the NVIDIA driver landed in #14778, so this PR mirrors that structure with two vLLM-specific adjustments.

This PR replaces the stub with a real implementation against vLLM's /v1/rerank:

  • POST {baseURL}/rerank
  • Request body: {"model": "<modelName>", "query": "<query>", "documents": [...], "top_n": <int>} — documents are a flat []string, not wrapped as {text: "..."} like NVIDIA's /ranking.
  • Response body: {"results": [{"index": int, "relevance_score": float}, ...]} (Jina-compatible; the optional document field is ignored since callers reconstruct text via Index).
  • Authorization: Bearer <ApiKey> is set only when APIConfig.ApiKey is non-empty, matching the existing Embed/ListModels behaviour in this file. vLLM is a local driver and can be deployed without an API key.

The return shape matches the existing *RerankResponse contract used by the NVIDIA (nvidia.go:461), Aliyun (aliyun.go:507), and ZhipuAI (zhipu-ai.go:554) drivers, i.e. Data []RerankResult carrying {Index, RelevanceScore} in the API's ranking order. Callers that need original-input order sort by Index.

Behaviour requirements from the issue, all covered:

  1. Empty documents → returns &RerankResponse{} without an HTTP call.
  2. Missing modelName → "model name is required" validation error.
  3. rerankConfig.TopN honored when 0 < TopN < len(documents); otherwise top_n defaults to len(documents) so callers get a score per input.
  4. Non-200 responses return an error including upstream status and body ("vLLM rerank API error: <status>, body: <body>").
  5. Response index values are bounds-checked against len(documents).

Scope:

  • internal/entity/models/vllm.go — replaces the Rerank stub at line 551 with a real implementation; adds vllmRerankRequest/vllmRerankResponse types for the slim subset of the payload we need. Region/baseURL resolution, 30s context timeout, conditional bearer header, and error wrapping all follow the existing patterns in this file.
  • conf/models/vllm.json — adds "rerank": "rerank" to url_suffix, joined to the operator-configured vLLM base URL the same way the NVIDIA driver joins at nvidia.go:485.
  • internal/entity/models/vllm_rerank_test.go — adds 7 httptest-backed tests mirroring nvidia_rerank_test.go: happy path (out-of-order ranking → Index preservation), top_n clamp to RerankConfig.TopN, empty-documents short-circuit, missing-model-name validation, HTTP error propagation, out-of-range index rejection, and a vLLM-specific TestVllmRerankWithoutAPIKey locking in the optional-auth behaviour that distinguishes this driver from NVIDIA.

Out of scope: no interface change, no DDL, no frontend change. Chat, embeddings, and balance paths are untouched. No new user-facing docs required beyond the existing rerank model setup page — vLLM joins the list of providers whose rerank model can be selected once /v1/rerank is exposed by the server.

Type of change

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

Replace the VllmModel.Rerank stub with a real implementation against
vLLM's Jina/Cohere-compatible /v1/rerank endpoint (stable since v0.7).

Mirrors the NVIDIA driver shape (infiniflow#14778) with two vLLM-specific
adjustments:

- documents is sent as a flat []string rather than [{text: "..."}]
- Authorization header is set only when APIConfig.ApiKey is non-empty,
  matching the local-deploy semantics of the existing Embed/ListModels
  paths in this file

Defaults top_n to len(documents) so callers get a score per input;
honors RerankConfig.TopN only when 0 < TopN < len(documents). Bounds-
checks response indices against the input slice. No interface change,
no DDL, no frontend change.

Wires "rerank": "rerank" into conf/models/vllm.json url_suffix so the
existing baseURL join used by Embed/ListModels reaches /v1/rerank.

Adds vllm_rerank_test.go covering happy path, top_n clamp, empty
documents, missing model name, optional-API-key (vLLM-specific),
HTTP error propagation, and out-of-range index rejection.
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label May 13, 2026
@coderabbitai

coderabbitai Bot commented May 13, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR implements vLLM reranking support by adding the /v1/rerank endpoint configuration, implementing the Rerank method with input validation and result parsing, and providing comprehensive test coverage for request/response handling, error cases, and edge conditions.

Changes

vLLM Rerank Feature

Layer / File(s) Summary
Configuration and API Contract
conf/models/vllm.json, internal/entity/models/vllm.go
Adds "rerank": "rerank" URL suffix to vLLM config and defines vllmRerankRequest and vllmRerankResponse structs for Jina/Cohere-compatible /v1/rerank endpoint shape.
Rerank Endpoint Implementation
internal/entity/models/vllm.go
Implements (*VllmModel).Rerank with input validation, region-based base URL resolution, conditional Authorization header, 30s timeout, result parsing, and index bounds checking. Returns scores in API ranking order.
Test Suite
internal/entity/models/vllm_rerank_test.go
HTTP mock server helper, test fixture builder, and seven test functions validating happy-path result parsing, top_n clamping, empty documents, Authorization header omission when API key is unset, model name requirement, HTTP error rejection, and out-of-bounds index validation.

Sequence Diagram

sequenceDiagram
  participant Caller
  participant VllmModel
  participant vLLMAPI as vLLM API
  Caller->>VllmModel: Rerank(modelName, query, documents)
  VllmModel->>VllmModel: Validate inputs and region
  VllmModel->>vLLMAPI: POST /v1/rerank with model, query, documents, top_n
  note over vLLMAPI: Authorization header<br/>set only if ApiKey present
  vLLMAPI-->>VllmModel: {results: [{index, relevance_score}]}
  VllmModel->>VllmModel: Validate returned indices within bounds
  VllmModel-->>Caller: RerankResponse{Data: []RerankResult}
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • infiniflow/ragflow#14735: Earlier iteration on vLLM rerank implementation that introduced the updated method signature.

Suggested labels

ci

Suggested reviewers

  • Haruko386

Poem

🐰 A vLLM rerank joins the fray,
With structs and tests to save the day,
No API keys? No problem there,
Out-of-bounds? We catch with care! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 11.11% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: implementing the Rerank function in the vLLM driver, which is directly reflected in the changeset.
Linked Issues check ✅ Passed All requirements from issue #14878 are met: Rerank implementation with proper request/response shapes, conditional Authorization header, TopN handling, empty documents short-circuit, model name validation, error handling with status/body, and bounds checking.
Out of Scope Changes check ✅ Passed All changes are directly in scope for the linked issue: vllm.go implementation, vllm.json configuration, and comprehensive test coverage; no unrelated modifications to chat, embeddings, or other components.
Description check ✅ Passed The PR description comprehensively addresses all required template sections with detailed technical context, clear problem statement, and explicit type of change selection.

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

@hunnyboy1217

Copy link
Copy Markdown
Contributor Author

Hi, @wangq8 ,
Could you please review my PR?

@JinHai-CN
JinHai-CN requested a review from Haruko386 May 14, 2026 06:48

@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 @hunnyboy1217, LGTM

@hunnyboy1217

Copy link
Copy Markdown
Contributor Author

Hi, @JinHai-CN ,
Could you please review this PR?

@Haruko386 Haruko386 added the ci Continue Integration label May 14, 2026
@JinHai-CN
JinHai-CN marked this pull request as draft May 15, 2026 02:20
@JinHai-CN
JinHai-CN marked this pull request as ready for review May 15, 2026 02:20
@codecov

codecov Bot commented May 15, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (39ee2fb) to head (002bea4).
⚠️ Report is 83 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14880   +/-   ##
=======================================
  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.

@hunnyboy1217

Copy link
Copy Markdown
Contributor Author

Hi, @JinHai-CN ,
All CI tests are successfully passed.
Could you please review this PR?

@JinHai-CN
JinHai-CN merged commit 86bcf97 into infiniflow:main May 15, 2026
1 check passed
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]: Go - implement Rerank in vLLM driver

3 participants