Repository navigation
Go: implement Rerank in ZhipuAI driver - #14608
Conversation
The ZhipuAI Go driver had a stub Rerank method that returned
"not implemented", even though conf/models/zhipu-ai.json already
ships glm-rerank as a rerank model and the rerank URL suffix is
already wired in url_suffix.
A tenant who picked glm-rerank in the Go layer could not actually
run a rerank call. This commit adds the real implementation so
the listed model works end to end.
How it works:
- POST to ${BaseURL}/${URLSuffix.Rerank} (resolves to
https://open.bigmodel.cn/api/paas/v4/rerank with the default
config) using the existing httpClient on the driver.
- Validate apiConfig and the API key, validate the model name,
and resolve the region. Return a clear local error before any
HTTP call when something is missing.
- Send {model, query, documents, top_n, return_documents:false}
in the body, the same OpenAI-compatible shape the SiliconFlow
driver already uses for its rerank call.
- Walk 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 results in a
different order.
Empty texts input returns an empty []float64 with no HTTP call.
Non-200 responses propagate the upstream status line and body.
Closes infiniflow#14607
|
Hi @Magicbook1108, gentle ping for review. This follows the same pattern as the existing SiliconFlow Rerank, scope is one file, and it closes #14607. Thanks! |
📝 WalkthroughWalkthroughThe PR implements the ChangesZhipuAI Rerank Implementation
Sequence DiagramsequenceDiagram
participant Client as Caller
participant ZhipuAI as ZhipuAIModel
participant HTTP as HTTP Client
participant Endpoint as ZhipuAI Service
Client->>ZhipuAI: Rerank(modelName, query, texts[], apiConfig)
ZhipuAI->>ZhipuAI: Validate inputs & select base URL by region
ZhipuAI->>ZhipuAI: Build zhipuRerankRequest payload
ZhipuAI->>HTTP: POST /api/paas/v4/rerank<br/>(with Bearer auth)
HTTP->>Endpoint: Send rerank request
Endpoint-->>HTTP: Return JSON response
HTTP-->>ZhipuAI: HTTP status + body
ZhipuAI->>ZhipuAI: Parse zhipuRerankResponse
ZhipuAI->>ZhipuAI: Extract & align scores to input order
ZhipuAI-->>Client: Return []float64 scores
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~22 minutes 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.
🧹 Nitpick comments (1)
internal/entity/models/zhipu-ai.go (1)
553-565: ⚡ Quick winPer-call context deadline is missing despite being stated as an objective.
PR objectives call out: "Use a per-call context deadline to avoid blocking", but this implementation uses
http.NewRequest(no context) and relies solely onz.httpClient.Timeout(120s) as a backstop. That timeout is a global setting on the shared client and is not per-call cancellable. Considerhttp.NewRequestWithContextwith acontext.WithTimeoutso callers/tests get proper cancellation semantics and the deadline is explicit at this call site.♻️ Suggested change
@@ import ( "bufio" "bytes" + "context" "encoding/json" "fmt" "io" "net/http" "ragflow/internal/common" "strings" "time" ) @@ - req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) - if err != nil { - return nil, fmt.Errorf("failed to create request: %w", err) - } + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + 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/zhipu-ai.go` around lines 553 - 565, The request currently uses http.NewRequest and relies on z.httpClient.Timeout; replace this with a per-call cancellable context by creating a ctx, cancel := context.WithTimeout(parentCtxOrBackground, desiredTimeout) and use http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(jsonData)); call defer cancel() after creation and then use z.httpClient.Do(req) as before so the call is cancellable independently of the shared client's Timeout; ensure you keep resp.Body.Close() handling and include the same headers (e.g., Authorization with *apiConfig.ApiKey).
🤖 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 `@internal/entity/models/zhipu-ai.go`:
- Around line 553-565: The request currently uses http.NewRequest and relies on
z.httpClient.Timeout; replace this with a per-call cancellable context by
creating a ctx, cancel := context.WithTimeout(parentCtxOrBackground,
desiredTimeout) and use http.NewRequestWithContext(ctx, "POST", url,
bytes.NewBuffer(jsonData)); call defer cancel() after creation and then use
z.httpClient.Do(req) as before so the call is cancellable independently of the
shared client's Timeout; ensure you keep resp.Body.Close() handling and include
the same headers (e.g., Authorization with *apiConfig.ApiKey).
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 147f054c-356a-436d-9322-f2144f2d0f64
📒 Files selected for processing (1)
internal/entity/models/zhipu-ai.go
Haruko386
left a comment
There was a problem hiding this comment.
Hi @pandadev66, LGTM
Thanks for the contribution. I have reviewed the implementation of the Zhipu AI Rerank endpoint. The core logic successfully mirrors our existing standard API.
While the code structure is highly robust, we may need to conduct further integration testing in the future to fully verify its overall feasibility and stability in RAGflows.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14608 +/- ##
=======================================
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 (#14608).
Closes #14655
### 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
## 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 ZhipuAI Go driver had a stub Rerank method that returned "not
implemented", even though conf/models/zhipu-ai.json already ships
glm-rerank as a rerank model and the rerank URL suffix is already wired
in url_suffix:
```json
"url_suffix": {
...
"rerank": "rerank"
},
"models": [
{"name": "glm-rerank", "model_types": ["rerank"]},
...
]
```
So the config was ready but the driver was not. A tenant who picked
glm-rerank in the Go layer could not actually run a rerank call. This PR
fills the gap so the listed model works end to end.
### What this PR includes
- `internal/entity/models/zhipu-ai.go`: real implementation of
`ZhipuAIModel.Rerank`, plus two small local types (`zhipuRerankRequest`,
`zhipuRerankResponse`) that mirror the standard OpenAI-compatible rerank
shape used by SiliconFlow.
No factory change. No JSON change. No interface change.
### How the driver works
- POST to `${BaseURL}/${URLSuffix.Rerank}` (resolves to
`https://open.bigmodel.cn/api/paas/v4/rerank` with the default config),
reusing the existing httpClient on the driver.
- Validate apiConfig and the API key, validate the model name, and
resolve the region. Return a clear local error before any HTTP call when
something is missing.
- Send `{model, query, documents, top_n, return_documents: false}` in
the body, the same shape the SiliconFlow driver already uses.
- Walk `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 results in a different order.
- Empty `texts` input returns an empty `[]float64` with no HTTP call.
- 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 (the
go.mod minimum) returns exit 0.
- The full method set on `ZhipuAIModel` still matches the `ModelDriver`
interface (NewInstance, Name, ChatWithMessages, ChatStreamlyWithSender,
Encode, ListModels, Balance, CheckConnection, Rerank).
- Pattern parity with the existing SiliconFlow Rerank implementation
(`internal/entity/models/siliconflow.go`).
Closes infiniflow#14607
### 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
## 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 ZhipuAI Go driver had a stub Rerank method that returned "not implemented", even though conf/models/zhipu-ai.json already ships glm-rerank as a rerank model and the rerank URL suffix is already wired in url_suffix:
So the config was ready but the driver was not. A tenant who picked glm-rerank in the Go layer could not actually run a rerank call. This PR fills the gap so the listed model works end to end.
What this PR includes
internal/entity/models/zhipu-ai.go: real implementation ofZhipuAIModel.Rerank, plus two small local types (zhipuRerankRequest,zhipuRerankResponse) that mirror the standard OpenAI-compatible rerank shape used by SiliconFlow.No factory change. No JSON change. No interface change.
How the driver works
${BaseURL}/${URLSuffix.Rerank}(resolves tohttps://open.bigmodel.cn/api/paas/v4/rerankwith the default config), reusing the existing httpClient on the driver.{model, query, documents, top_n, return_documents: false}in the body, the same shape the SiliconFlow driver already uses.results[*].relevance_scoreand copy each score into the output slice indexed byresults[*].index, so the output order matches the input order even if the API returns results in a different order.textsinput returns an empty[]float64with no HTTP call.Type of change
How was this tested?
go build ./internal/entity/models/...in a clean go 1.25 image (the go.mod minimum) returns exit 0.ZhipuAIModelstill matches theModelDriverinterface (NewInstance, Name, ChatWithMessages, ChatStreamlyWithSender, Encode, ListModels, Balance, CheckConnection, Rerank).internal/entity/models/siliconflow.go).Closes #14607