Skip to content

Go: implement provider: Voyage AI - #14811

Merged
JinHai-CN merged 9 commits into
infiniflow:mainfrom
tmimmanuel:go/localai-embed
May 14, 2026
Merged

JinHai-CN merged 9 commits into
infiniflow:mainfrom
tmimmanuel:go/localai-embed

Conversation

@tmimmanuel

@tmimmanuel tmimmanuel commented May 12, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Add a Go driver for Voyage AI (https://voyageai.com), one of the unchecked providers on the umbrella tracking issue #14736. Voyage AI is embed + rerank only — no chat, no streaming, no /v1/models endpoint. It's the first provider in the Go layer of this shape.

Until this PR, a tenant who configured voyage as a model provider in the Go layer fell through to the default branch of internal/entity/models/factory.go and got the dummy driver.

What this PR includes

  • New internal/entity/models/voyage.go with a VoyageModel implementing the ModelDriver interface.
  • New conf/models/voyage.json with 6 embedding models (voyage-3.5, voyage-3.5-lite, voyage-3-large, voyage-code-3, voyage-law-2, voyage-finance-2) and 2 rerank models (rerank-2, rerank-2-lite).
  • factory.go: route "voyage" to NewVoyageModel.
  • internal/entity/models/voyage_test.go: 19 unit tests.

How the driver works

  • Embed: POST /v1/embeddings. Response is OpenAI-shaped ({data: [{embedding, index, object, text}], model, usage}). Driver reorders by index, rejects duplicate / out-of-range / missing slots, and short-circuits empty input without an HTTP call.
  • Rerank: POST /v1/rerank. Voyage uses top_k as the request param name (not top_n like Aliyun/SiliconFlow); the driver translates RerankConfig.TopN → top_k. Response is Cohere-shaped ({data: [{relevance_score, index}], model}), so the existing RerankResponse{Data: []RerankResult{Index, RelevanceScore}} shape fits cleanly.
  • ListModels: returns a hardcoded list of voyageKnownModels. Voyage does not expose /v1/models (probed live, returns 404), so the driver synthesizes the list from the same set the config ships. New upstream models are added by extending one slice.
  • CheckConnection: pings a 1-input embed call against voyage-3.5. Without /v1/models, this is the cheapest way to verify the API key + network path before a tenant tries a real workload.
  • ChatWithMessages / ChatStreamlyWithSender / Balance / TranscribeAudio / AudioSpeech / OCRFile: all return "no such method". Voyage does not host any of these surfaces.

No interface change. No new dependencies.

How was this tested?

19 unit tests in internal/entity/models/voyage_test.go — all pass on go 1.25:

$ go test -vet=off -run TestVoyage -count=1 ./internal/entity/models/...
ok      ragflow/internal/entity/models  0.036s

Coverage: Name; Embed (happy path, reorder, empty-input, missing key/model, duplicate index, out-of-range index, missing slot); Rerank (happy path with top_k assertion, default-to-len-documents, empty documents, out-of-range index); ListModels (static list, missing key); CheckConnection (happy, 401); chat methods sentinels; Balance sentinel; audio/OCR sentinels.

go build ./internal/entity/models/... exits 0.

Live integration test against api.voyageai.com:

=== RUN   TestVoyageLiveSmoke
    [OK] Name() = "voyage"
    [OK] ListModels (static): 8 models -> [voyage-3.5 voyage-3.5-lite voyage-3-large voyage-code-3 voyage-law-2 voyage-finance-2 rerank-2 rerank-2-lite]
    [OK] CheckConnection
    [OK] Embed vectors=3 dim=1024 indices=[0 1 2]
    [OK] Embed(empty) -> 0 vectors
    [OK] Rerank results=3 scores=[0.8125 0.59765625 0.39453125]
    [OK] ChatWithMessages returns voyage, no such method
    [OK] Balance returns voyage, no such method

VOYAGE LIVE SMOKE PASSED
--- PASS: TestVoyageLiveSmoke (0.81s)

What the live run proves on the wire:

  • Auth (Bearer <key>) accepted by api.voyageai.com.
  • Embed voyage-3.5 on 3 inputs returns 3 vectors at dim 1024 with index field preserved as [0, 1, 2] — the reorder-by-index code is exercised on real data.
  • Empty input short-circuits without an HTTP call (mock server would have been hit if it did).
  • Rerank rerank-2 on 3 docs returns 3 real relevance_score floats [0.8125, 0.598, 0.395]. The top_k translation works on the live wire.
  • All sentinel methods return the documented "no such method" strings.

Note on PR history

This branch was previously named for LocalAI Embed work which is now consolidated into PR #14813. The branch was reset to upstream/main and rebuilt for Voyage. Diff against main is a clean +838 lines across 4 files.

Type of change

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

Tracking: #14736

@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label May 12, 2026
@coderabbitai

coderabbitai Bot commented May 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR adds a complete Voyage AI model driver to RagFlow's embedding and reranking system. It registers the provider in the factory, implements embedding and reranking APIs with strict request/response validation and index reordering, provides model discovery and connection diagnostics, and includes comprehensive test coverage for all code paths and error cases.

Changes

Voyage AI Model Driver

Layer / File(s) Summary
Configuration and Factory Registration
conf/models/voyage.json, internal/entity/models/factory.go
VoyageAI configuration defines base URL and URL suffixes for embedding and reranking endpoints with 8 known models. Factory recognizes "voyage" provider (case-insensitive) and instantiates VoyageModel via NewVoyageModel.
Type Definition and HTTP Client Setup
internal/entity/models/voyage.go (lines 1–92)
VoyageModel struct with cloned HTTP transport and tuned connection-pool/timeout parameters. NewVoyageModel constructor, NewInstance factory method, Name returning "voyage", and baseURLForRegion helper for region-aware URL resolution.
Embed API Implementation
internal/entity/models/voyage.go (lines 94–215)
Embed request/response types and Embed method: validates non-empty input, API key, model name; POSTs to /embeddings; reorders returned embeddings by strict index validation (catching duplicates, out-of-range, and missing slots).
Rerank API Implementation
internal/entity/models/voyage.go (lines 217–319)
Rerank request/response types and Rerank method: validates non-empty documents, API key, model name; POSTs to /rerank with top_k derived from TopN (defaulting to document count); maps (index, relevance_score) pairs into RerankResponse with index bounds validation.
Model Discovery and Diagnostics
internal/entity/models/voyage.go (lines 321–343)
ListModels returns static known models after API key validation. CheckConnection delegates to Embed with voyage-3.5 on single input to verify connectivity.
Unsupported Method Stubs
internal/entity/models/voyage.go (lines 345–379)
Chat, balance, transcription, TTS, and OCR methods return consistent "<voyage>, no such method" errors.
Test Suite
internal/entity/models/voyage_test.go (lines 1–388)
20 test functions covering Name, Embed (happy path, index reordering, empty-input short-circuit, validation errors for API key/model/indices), Rerank (happy path, top_k defaults, empty documents, index validation), ListModels/CheckConnection (with API key and 401 authorization checks), and unsupported method stubs; uses local HTTP server mock with Bearer token and JSON validation.

Sequence Diagram(s)

sequenceDiagram
  participant Caller as Client Code
  participant Voyage as VoyageModel
  participant HTTP as Voyage API Server
  participant Parse as JSON Parser
  
  Caller->>Voyage: Embed(model, texts, apiConfig)
  Voyage->>Voyage: validate inputs/API key/model
  Voyage->>HTTP: POST /v1/embeddings {model, input}
  HTTP->>Parse: validate response
  Parse->>Voyage: {data: [{index, embedding}]}
  Voyage->>Voyage: reorder by index (validate bounds)
  Voyage->>Caller: []EmbeddingData (ordered)
Loading
sequenceDiagram
  participant Caller as Client Code
  participant Voyage as VoyageModel
  participant HTTP as Voyage API Server
  participant Parse as JSON Parser
  
  Caller->>Voyage: Rerank(model, query, docs, config)
  Voyage->>Voyage: validate documents/API key/model
  Voyage->>HTTP: POST /v1/rerank {model, query, documents, top_k}
  HTTP->>Parse: validate response
  Parse->>Voyage: {results: [{index, relevance_score}]}
  Voyage->>Voyage: map indices to RerankResponse
  Voyage->>Caller: *RerankResponse (mapped)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related issues

Possibly related PRs

  • infiniflow/ragflow#14605: Modifies internal/entity/models/factory.go to register a new provider in CreateModelDriver (same wiring pattern).
  • infiniflow/ragflow#14700: Adds embedding support (Encode) in NVIDIA driver with similar request/response validation, input handling, and index-based result mapping.
  • infiniflow/ragflow#14807: Adds Mistral model driver with similar factory registration and embedding/reranking implementation patterns.

Suggested labels

💞 feature, size:L

Suggested reviewers

  • Haruko386

Poem

🐰 Voyage takes flight with embeddings true,
Reranking results in order they flew,
Index by index, no dupes in sight,
RAG flows end-to-end with vectors bright! ✨

🚥 Pre-merge checks | ✅ 1 | ❌ 4

❌ Failed checks (4 warnings)

Check name Status Explanation Resolution
Title check ⚠️ Warning The PR title references implementing a Voyage AI provider, but the linked issue #14810 is about implementing Embed for LocalAI, not Voyage. This is a mismatch. Verify that the correct linked issue is associated with this PR. The title should match the actual issue being solved (either update the issue link or correct the title).
Linked Issues check ⚠️ Warning The PR implements Voyage AI support per the description, but the linked issue #14810 requests LocalAI Embed implementation. The code changes do not address the LocalAI feature request in the linked issue. Either link the correct Voyage AI tracking issue or ensure the PR implementation matches the linked issue requirements.
Out of Scope Changes check ⚠️ Warning The PR implements Voyage AI (embedding + reranking) which is completely unrelated to the linked issue #14810 that requests LocalAI Embed implementation. This represents a scope mismatch between the linked issue and actual changes. Align the linked issues with the actual PR scope or update the PR to address the requirements in the linked issue.
Docstring Coverage ⚠️ Warning Docstring coverage is 10.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (1 passed)
Check name Status Explanation
Description check ✅ Passed The PR description comprehensively covers what problem is solved, the type of change, implementation details, testing approach, and includes context about the PR history.

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

🤖 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/localai.go`:
- Around line 284-285: The request currently uses context.Background() in the
call to http.NewRequestWithContext which can hang if the server stalls; replace
it with a cancellable context (e.g., ctx, cancel :=
context.WithTimeout(context.Background(), 30*time.Second); defer cancel()) or
accept/pass through a caller context, then use that ctx in NewRequestWithContext
and ensure the httpClient (used for the stream request) respects cancellation;
make the timeout configurable rather than hard-coding if needed and reference
the http.NewRequestWithContext call, httpClient, url and jsonData places in
localai.go.
🪄 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: 0b5f1a3b-5fee-4861-8016-8ff05d3fe4c8

📥 Commits

Reviewing files that changed from the base of the PR and between 2f2d156 and 9b528d1.

📒 Files selected for processing (3)
  • conf/models/localai.json
  • internal/entity/models/factory.go
  • internal/entity/models/localai.go

Comment thread internal/entity/models/localai.go Resolved
tmimmanuel added a commit to tmimmanuel/ragflow that referenced this pull request May 12, 2026
CodeRabbit review on the stacked PR infiniflow#14811 flagged that the
ChatStreamlyWithSender comment promised "the client drops the
connection if it stalls", which is not actually implemented in the
current driver. Replace the comment with the more accurate wording
used in the merged OpenAI driver (infiniflow#14605): the background context
makes the request "cancellable in principle" but no hard deadline is
attached because SSE streams are long-lived, and threading a real
ctx through the ModelDriver interface is a wider change for a
follow-up.

Also add a nil-sender guard at the top of ChatStreamlyWithSender,
matching the fixes applied to Mistral (infiniflow#14805) and Upstage (infiniflow#14817)
on review feedback. The risk class is the same: invoking a nil
callback panics the process.
@tmimmanuel tmimmanuel mentioned this pull request May 12, 2026
1 task done

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

13-226: ⚡ Quick win

Add unit coverage for the new Embed path.

This suite covers chat/stream/auth, but the new embeddings flow still has no deterministic unit tests. Please add cases for empty-input short-circuit, index reordering, and malformed/duplicate data[*].index responses so Embed's contract stays protected without relying on smoke runs.

🤖 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/localai_test.go` around lines 13 - 226, Add
deterministic unit tests for the new embeddings path by creating three new test
functions in internal/entity/models/localai_test.go that exercise LocalAIModel.
Specifically, write: (1) TestLocalAIEmbedShortCircuitsOnEmptyInput — call
LocalAIModel.Embed (or EmbedWithSender if that’s the API) with an empty input
slice and assert it returns immediately with no network calls/zero embeddings;
(2) TestLocalAIEmbedHandlesReorderedIndices — have httptest.NewServer return a
JSON body whose data array contains embeddings out of order (data[*].index
values not sequential) and assert the returned embeddings are reordered to match
the input order; and (3) TestLocalAIEmbedDetectsMalformedOrDuplicateIndex — have
the server return responses with missing/invalid index fields and with duplicate
data[*].index values and assert the Embed call returns a clear error in each
case. Use newLocalAIForTest(srv.URL), APIConfig stubs as in other tests, and
check errors/messages contain descriptive text (e.g., "invalid index" or
"duplicate index") to lock the contract.
🤖 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/localai.go`:
- Around line 518-527: The loop over parsed.Data currently overwrites duplicate
indices silently; update the block inside the for loop that processes
parsed.Data (the code assigning to embeddings[item.Index] and setting
filled[item.Index]) to check if filled[item.Index] is already true and, if so,
return an error (e.g., fmt.Errorf("localai: duplicate response index %d") )
instead of overwriting; this change should be made in the same function handling
parsed.Data and use the existing embeddings, filled, and EmbeddingData symbols
to locate the code.

---

Nitpick comments:
In `@internal/entity/models/localai_test.go`:
- Around line 13-226: Add deterministic unit tests for the new embeddings path
by creating three new test functions in internal/entity/models/localai_test.go
that exercise LocalAIModel. Specifically, write: (1)
TestLocalAIEmbedShortCircuitsOnEmptyInput — call LocalAIModel.Embed (or
EmbedWithSender if that’s the API) with an empty input slice and assert it
returns immediately with no network calls/zero embeddings; (2)
TestLocalAIEmbedHandlesReorderedIndices — have httptest.NewServer return a JSON
body whose data array contains embeddings out of order (data[*].index values not
sequential) and assert the returned embeddings are reordered to match the input
order; and (3) TestLocalAIEmbedDetectsMalformedOrDuplicateIndex — have the
server return responses with missing/invalid index fields and with duplicate
data[*].index values and assert the Embed call returns a clear error in each
case. Use newLocalAIForTest(srv.URL), APIConfig stubs as in other tests, and
check errors/messages contain descriptive text (e.g., "invalid index" or
"duplicate index") to lock the contract.
🪄 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: 66d0471c-a099-45bd-9b60-be2dd17818dd

📥 Commits

Reviewing files that changed from the base of the PR and between c72f278 and f08a7ef.

📒 Files selected for processing (3)
  • conf/models/localai.json
  • internal/entity/models/localai.go
  • internal/entity/models/localai_test.go
✅ Files skipped from review due to trivial changes (1)
  • conf/models/localai.json

Comment thread internal/entity/models/localai.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.

🧹 Nitpick comments (1)
internal/entity/models/localai_test.go (1)

51-56: ⚡ Quick win

Simplify the cleanup-order explanation.

The comment correctly explains the cleanup order at the end, but the middle portion ("wait, that's the opposite") introduces unnecessary confusion. The actual code is correct: t.Cleanup runs in LIFO order, so registering srv.Close first (line 74) and close(hold) second (line 75) ensures close(hold) runs first, allowing the handler to exit cleanly.

📝 Clearer comment
-	// hold blocks the handler until the test closes it. Register
-	// close(hold) FIRST so it runs LAST (defers are LIFO) — wait,
-	// that's the opposite. We want close(hold) to run BEFORE
-	// srv.Close() so the handler can return. Use t.Cleanup, which
-	// runs in reverse-registration order: register srv.Close first
-	// so it runs last, then close(hold) so it runs first.
+	// hold blocks the handler until the test closes it.
+	// t.Cleanup runs in LIFO order: register srv.Close first
+	// (runs last), then close(hold) (runs first), so the handler
+	// can exit before the server shuts down.
🤖 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/localai_test.go` around lines 51 - 56, Replace the
verbose/confused comment explaining cleanup order with a concise one that states
t.Cleanup runs in LIFO order and therefore registering srv.Close before
close(hold) ensures close(hold) runs first so the handler can exit; reference
the registrations for srv.Close and close(hold) in
internal/entity/models/localai_test.go to locate where to update the comment.
🤖 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/localai_test.go`:
- Around line 51-56: Replace the verbose/confused comment explaining cleanup
order with a concise one that states t.Cleanup runs in LIFO order and therefore
registering srv.Close before close(hold) ensures close(hold) runs first so the
handler can exit; reference the registrations for srv.Close and close(hold) in
internal/entity/models/localai_test.go to locate where to update the comment.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: ed00e0a8-8040-44f5-af5d-0210f5d7714c

📥 Commits

Reviewing files that changed from the base of the PR and between f08a7ef and 7390d95.

📒 Files selected for processing (2)
  • internal/entity/models/localai.go
  • internal/entity/models/localai_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/entity/models/localai.go

@JinHai-CN

Copy link
Copy Markdown
Member

Duplicated with #14813. I will close it. Please feel free to re-open it, if i am wrong.

@JinHai-CN JinHai-CN closed this May 12, 2026
@JinHai-CN JinHai-CN reopened this May 12, 2026
@tmimmanuel tmimmanuel closed this May 12, 2026
@dosubot dosubot Bot added size:XS This PR changes 0-9 lines, ignoring generated files. and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels May 12, 2026
Voyage AI (https://voyageai.com) is one of the unchecked providers on
the umbrella tracking issue infiniflow#14736. Unlike the other Go drivers, Voyage
is embed/rerank only — no chat, no streaming, no /v1/models endpoint.

What this PR includes:

- internal/entity/models/voyage.go: full driver, ~290 lines
- conf/models/voyage.json: 8 models (6 embedding + 2 rerank)
- factory.go: route "voyage" to NewVoyageModel
- internal/entity/models/voyage_test.go: 19 unit tests

Methods:

- Embed: POST /v1/embeddings, reorder-by-index, empty-input
  short-circuit, duplicate/out-of-range/missing-slot rejection
- Rerank: POST /v1/rerank. Voyage uses `top_k` as the request param
  name (not `top_n` like Aliyun/SiliconFlow); the driver translates
  RerankConfig.TopN -> top_k. Same Cohere-shaped response.
- ListModels: returns voyageKnownModels (hardcoded). Voyage does
  NOT expose /v1/models (probed live, returns 404), so the driver
  synthesizes the list from the same set the config ships.
- CheckConnection: pings a 1-input embed call against voyage-3.5
  — cheapest way to verify the API key + network path without
  a /v1/models endpoint.
- ChatWithMessages / ChatStreamlyWithSender / Balance /
  TranscribeAudio / AudioSpeech / OCRFile: all return
  "no such method" (Voyage does not host any of these surfaces).

19 unit tests pass on go 1.25; build clean.

Verified live against api.voyageai.com:
- ListModels: 8 ids (static)
- Embed (voyage-3.5): 3 vectors at dim 1024, indices preserved
  [0, 1, 2]
- Embed empty input: 0 vectors, no HTTP call
- Rerank (rerank-2) on 3 docs: real scores [0.8125, 0.598, 0.395]
- CheckConnection: ok (1-input embed succeeds)
- Sentinels: all return "no such method"

Note on PR history: this branch was previously named for LocalAI
Embed work which has since been consolidated into PR infiniflow#14813. The
branch was reset to upstream/main and rebuilt for Voyage — diff is
a clean +800 lines on top of current main.
@tmimmanuel tmimmanuel reopened this May 12, 2026
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:XS This PR changes 0-9 lines, ignoring generated files. labels May 12, 2026
@tmimmanuel tmimmanuel changed the title Go: implement Embed (embeddings) in LocalAI driver Go: implement provider: Voyage AI May 12, 2026

@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 (2)
internal/entity/models/voyage.go (2)

307-316: 💤 Low value

Consider validating for duplicate indices in Rerank response.

Embed strictly rejects duplicate indices (lines 199–201) to detect malformed API responses. Rerank validates out-of-range indices but does not check for duplicates. Although top_k filtering means fewer results are expected, a duplicate index would still indicate a malformed response. Adding a duplicate check would align Rerank's validation with Embed's defensive posture.

♻️ Optional: add duplicate-index check in Rerank
 	rerankResponse := &RerankResponse{}
+	seen := make(map[int]bool)
 	for _, r := range parsed.Data {
 		if r.Index < 0 || r.Index >= len(documents) {
 			return nil, fmt.Errorf("voyage: rerank result index %d out of range for %d documents", r.Index, len(documents))
 		}
+		if seen[r.Index] {
+			return nil, fmt.Errorf("voyage: duplicate rerank index %d in response", r.Index)
+		}
+		seen[r.Index] = true
 		rerankResponse.Data = append(rerankResponse.Data, RerankResult{
🤖 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/voyage.go` around lines 307 - 316, The Rerank parsing
loop in the code that builds RerankResponse (iterating parsed.Data and appending
RerankResult) currently checks for out-of-range indices but not duplicates;
modify the loop in the Rerank handling (where parsed.Data is processed into
rerankResponse.Data and RerankResult is constructed) to track seen indices
(e.g., a map[int]bool), and if an index is encountered twice return an error
such as "voyage: duplicate rerank result index %d" instead of appending; ensure
the duplicate check runs before appending so Rerank validation mirrors Embed's
defensive duplicate-index rejection.

146-146: ⚡ Quick win

Inconsistent URL construction between Embed and Rerank.

Rerank (line 257) defensively calls strings.TrimSuffix(baseURL, "/") before appending the suffix, but Embed (line 146) does not. If a tenant's baseURL ends with a trailing slash and URLSuffix.Embedding does not start with one, Embed would produce a double-slash URL (http://api/.../v1//embeddings). For consistency and robustness, apply the same trimming in both methods.

🔧 Proposed fix: trim baseURL in Embed
-	url := fmt.Sprintf("%s/%s", baseURL, v.URLSuffix.Embedding)
+	url := fmt.Sprintf("%s/%s", strings.TrimSuffix(baseURL, "/"), v.URLSuffix.Embedding)

Also applies to: 257-257

🤖 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/voyage.go` at line 146, The Embed URL builder in
method Embed currently concatenates baseURL and v.URLSuffix.Embedding directly
and can produce a double-slash if baseURL ends with “/”; change the construction
to trim any trailing slash from baseURL (use strings.TrimSuffix(baseURL, "/"))
before appending v.URLSuffix.Embedding (same approach as Rerank), and ensure
strings is imported/used so the new call compiles.
🤖 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/voyage.go`:
- Around line 307-316: The Rerank parsing loop in the code that builds
RerankResponse (iterating parsed.Data and appending RerankResult) currently
checks for out-of-range indices but not duplicates; modify the loop in the
Rerank handling (where parsed.Data is processed into rerankResponse.Data and
RerankResult is constructed) to track seen indices (e.g., a map[int]bool), and
if an index is encountered twice return an error such as "voyage: duplicate
rerank result index %d" instead of appending; ensure the duplicate check runs
before appending so Rerank validation mirrors Embed's defensive duplicate-index
rejection.
- Line 146: The Embed URL builder in method Embed currently concatenates baseURL
and v.URLSuffix.Embedding directly and can produce a double-slash if baseURL
ends with “/”; change the construction to trim any trailing slash from baseURL
(use strings.TrimSuffix(baseURL, "/")) before appending v.URLSuffix.Embedding
(same approach as Rerank), and ensure strings is imported/used so the new call
compiles.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 29ef2dd9-7534-4f68-a0d0-75a9d7b770e6

📥 Commits

Reviewing files that changed from the base of the PR and between 7390d95 and d25699e.

📒 Files selected for processing (4)
  • conf/models/voyage.json
  • internal/entity/models/factory.go
  • internal/entity/models/voyage.go
  • internal/entity/models/voyage_test.go
✅ Files skipped from review due to trivial changes (1)
  • conf/models/voyage.json

Address the two actionable CodeRabbit findings on PR infiniflow#14811:

- voyage.go Embed: trim a trailing slash off baseURL before joining
  with URLSuffix.Embedding, matching what Rerank already does. A
  tenant who configures baseURL as ".../v1/" would otherwise hit
  ".../v1//embeddings" and get a 404.
- voyage.go Rerank: reject duplicate response indices the same way
  Embed does. The earlier code only checked out-of-range; a
  duplicate slot would have silently appended both rows, hiding a
  malformed upstream response.

Tests:
- TestVoyageEmbedTrimsTrailingSlashInBaseURL pins the new behavior.
- TestVoyageRerankRejectsDuplicateIndex mirrors the existing
  TestVoyageEmbedRejectsDuplicateIndex.

Live-verified against api.voyageai.com on the current key: /v1/embeddings
returns OpenAI-shaped data for all six shipped embedding models,
/v1/rerank returns Cohere-shaped data with top_k for both shipped
rerank models, and /v1/models still 404s (justifying the static
ListModels catalog).
@tmimmanuel

Copy link
Copy Markdown
Contributor Author

Pushed 094e213 to address the two actionable CodeRabbit findings, and re-audited the API surface against the Voyage docs (https://docs.voyageai.com/reference/embeddings-api, https://docs.voyageai.com/reference/reranker-api) after the lesson from #14809.

CodeRabbit findings:

Finding Status
voyage.go:146 Embed URL doesn't TrimSuffix("/") like Rerank does Fixed
voyage.go:307-316 Rerank doesn't reject duplicate response indices like Embed does Fixed

Both are pinned by tests (TestVoyageEmbedTrimsTrailingSlashInBaseURL, TestVoyageRerankRejectsDuplicateIndex).

Docs vs code audit:

Surface Docs say Code does
Embed body fields input, model, input_type, truncation, output_dimension, output_dtype, encoding_format sends input, model only — subset of documented, no undocumented fields
Rerank body fields query, documents, model, top_k, truncation, return_documents sends query, documents, model, top_k — subset, no undocumented fields
top_k vs top_n docs say top_k RerankConfig.TopN → top_k translated
/v1/models endpoint not documented hardcoded voyageKnownModels (live-confirmed /v1/models 404s)

Optional documented fields (input_type, truncation, output_dimension, etc.) are not exposed because the current EmbeddingConfig / RerankConfig structs don't carry them — that's a feature-add for later, not an API-alignment fix.

Live re-test against api.voyageai.com on 094e213:

embeddings /v1/embeddings
  voyage-3.5       -> 200 (1024-d)
  voyage-3.5-lite  -> 200
  voyage-3-large   -> 200
  voyage-code-3    -> 200
  voyage-law-2     -> 200
  voyage-finance-2 -> 200 (429 once due to rate limit, retried)
rerank /v1/rerank
  rerank-2         -> 200, three docs scored, top match index=0 as expected
  rerank-2-lite    -> 200
models /v1/models  -> 404 (justifies hardcoded ListModels)

Re: the earlier "duplicated with #14813" note — #14813 is the LocalAI driver and is a separate PR. This one ships Voyage AI (embed + rerank only, no chat). Happy to rebase or split further if a maintainer prefers.

Cross-applying the lessons from the merged infiniflow#14790 sample driver and
from the maintainer's reviews on infiniflow#14809 and infiniflow#14850:

conf/models/voyage.json:
- name: "VoyageAI" -> "Voyage" (the maintainer's "remove AI suffix"
  guidance from infiniflow#14850).
- baseURL: "https://api.voyageai.com/v1" -> "https://api.voyageai.com"
  (bare URL; version moves into the suffix), matching the pattern
  used on Novita and the Cohere sample (api.cohere.com + v2/chat,
  v1/models).
- url_suffix.embedding: "embeddings" -> "v1/embeddings".
- url_suffix.rerank:    "rerank"     -> "v1/rerank".

internal/entity/models/voyage.go:
- Embed: forward EmbeddingConfig.Dimension as Voyage's documented
  `output_dimension` body field. This is the singular spelling per
  https://docs.voyageai.com/reference/embeddings-api ; Voyage rejects
  unknown fields with HTTP 400 (live-verified — sending "dimensions"
  returns "Argument 'dimensions' is not supported by our API"), so
  matching the docs spelling exactly is load-bearing. Live test
  against voyage-3.5 with output_dimension=256 trims the vector
  from the default 1024 to 256.

internal/entity/models/voyage_test.go:
- New: TestVoyageEmbedPropagatesOutputDimension pins the wire field
  name and guards against re-adding "dimensions" / "dimension".
- New: TestVoyageEmbedOmitsOutputDimensionWhenUnset — Voyage 400s on
  output_dimension: 0, so the key must be absent when Dimension is
  unset rather than sent as zero.
- All existing path-asserting tests updated to expect the new
  versioned suffixes (/v1/embeddings, /v1/rerank).
Cross-applying the maintainer guidance from
infiniflow#14809 (review):
"There is no need to implement the interface that is not officially
given."

The Voyage AI docs at https://docs.voyageai.com publish embeddings
and rerank endpoints only. There is no /v1/models surface (404 live-
confirmed) and no documented /health endpoint. ListModels and
CheckConnection were therefore inventing behaviour the upstream does
not expose:

- ListModels was returning a hardcoded voyageKnownModels slice that
  duplicated the shipped conf/models/voyage.json catalog.
- CheckConnection was burning a one-input embed call against
  voyage-3.5 per probe, which costs tenant quota and only
  retroactively validates the integration.

Both methods now return the standard `"<name>, no such method"`
sentinel, matching the convention every merged driver in this package
uses (including the Cohere sample in infiniflow#14790). The shipped catalog
in conf/models/voyage.json is unchanged and remains the source of
truth for which Voyage models RAGFlow knows about.

Dropped the corresponding sentinel-pinning tests; they were the
lowest-signal entries in the suite (asserting a constant string
return from an unimplemented method). 16 tests covering the actual
Embed and Rerank behaviour remain and pass.

@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 @tmimmanuel, Embed and Rerank is OK
plz change what I me mentioned

Comment thread internal/entity/models/voyage.go Resolved
Comment thread internal/entity/models/voyage.go Resolved
Comment thread conf/models/voyage.json Resolved
Comment thread conf/models/voyage.json Resolved
Comment thread conf/models/voyage.json Resolved
Comment thread conf/models/voyage.json Resolved
Comment thread conf/models/voyage.json Resolved
Maintainer review on commit 8a1662c flagged the per-model max_tokens
values in conf/models/voyage.json. Per
https://docs.voyageai.com/docs/embeddings :

  Total tokens per batch:
    1M    for voyage-3.5-lite (and voyage-4-lite)
    320K  for voyage-3.5 (and voyage-4, voyage-2)
    120K  for voyage-3-large, voyage-code-3, voyage-finance-2,
          voyage-law-2 (and voyage-4-large)

And per https://docs.voyageai.com/docs/reranker the per-query token
limits are:

  4,000 for rerank-2
  2,000 for rerank-2-lite

The previous values (32000 for every embedding model, 16000/8000 for
the rerank pair) were the per-document context windows, not the
per-call submission limits the ragflow `max_tokens` field is meant
to represent.

The voyage.go inline comments on the same review ("no hard code" on
line 107, "return `no such method`" on line 361) were already
addressed by 8a1662c — the hardcoded voyageKnownModels slice is
gone and both ListModels and CheckConnection return the documented
sentinel.
@tmimmanuel

Copy link
Copy Markdown
Contributor Author

@Haruko386 thanks — pushed 2c0a1b6 with the max_tokens corrections.

Line Model Was Now Source
13 voyage-3.5 32000 327680 (320×1024) embedding docs: "320K" batch tokens
21 voyage-3.5-lite 32000 1048576 (1024×1024) embedding docs: "1M" batch tokens
53 voyage-finance-2 32000 122880 (120×1024) embedding docs: "120K" batch tokens
56 rerank-2 16000 4000 rerank docs: per-query 4,000 tokens
63 rerank-2-lite 8000 2000 rerank docs: per-query 2,000 tokens

Also applied 120K to voyage-3-large, voyage-code-3, and voyage-law-2 since the docs group them in the same batch tier as voyage-finance-2 — keeping the catalog consistent with what the docs say.

The two voyage.go inline comments on the same review:

  • line 107 "no hard code" — the `voyageKnownModels` slice is gone (was removed in 8a1662c).
  • line 361 "return `no such method`" — `CheckConnection` returns the sentinel (also done in 8a1662c).

Tests still pass (16 covering Embed/Rerank wire shape + URL trim).

@tmimmanuel
tmimmanuel requested a review from Haruko386 May 13, 2026 04:50

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

@tmimmanuel Thank you for your contribution

JinHai-CN added a commit that referenced this pull request May 13, 2026
### What problem does this PR solve?

The LocalAI Go driver landed in #14809 and Embed landed in #14811.
`Rerank` was left as a stub that returns `"not implemented"`. This PR
fills the gap.

LocalAI exposes a public rerank endpoint at `<tenant-url>/v1/rerank`
with a Cohere-shaped request and response (`{model, query, documents,
top_n}` → `{results: [{index, relevance_score}]}`). The Python side has
had `LocalAIRerank` in `rag/llm/rerank_model.py` for a long time. Until
this PR, a tenant who wanted to use LocalAI for reranking in the Go
layer got `"not implemented"`.

### What this PR includes

- `conf/models/localai.json`: add `"rerank": "rerank"` under
`url_suffix` so the driver can build the URL from config. This matches
the `URLSuffix.Rerank` field already used by aliyun and siliconflow.
- `internal/entity/models/localai.go`: replace the `Rerank` stub with a
real implementation that POSTs to `/v1/rerank`. Adds local
request/response types `localAIRerankRequest` and
`localAIRerankResponse`.

No factory change. No interface change.

### How the implementation works

- Validate the model name and resolve the tenant-supplied base URL with
the existing `resolveBaseURL` helper.
- Wrap the request with `context.WithTimeout(nonStreamCallTimeout)` so
the call has a clear deadline. Same pattern `ChatWithMessages`,
`ListModels`, and `Embed` already use in this file.
- Only set the `Authorization` header when a non-empty API key was
supplied. LocalAI accepts an empty key by default, so this preserves the
optional-auth contract.
- Default `top_n` to `len(documents)` when `rerankConfig.TopN == 0`,
matching the existing Aliyun and SiliconFlow rerank implementations.
- Validate every `results[].index` against `len(documents)`. If the
upstream returns an out-of-range index, fail clearly instead of silently
writing past the slice.
- An empty `documents` slice returns `&RerankResponse{}` with no HTTP
call.
- Non-200 responses propagate the upstream status line and body.

### Note on stacking

This PR builds on #14809 (LocalAI driver) and #14811 (LocalAI Embed).
Until both merge, this PR's diff on GitHub will include all three
commits. After #14809 and #14811 land on `main`, GitHub will auto-reduce
this PR to only the `Rerank` changes (one commit, ~99 line diff in
`localai.go` plus 1 line in `localai.json`).

### Type of change

- [x] New Feature (non-breaking change which adds functionality)

### How was this tested?

- `go build ./internal/entity/models/...` returns exit 0 on go 1.25 (the
`go.mod` minimum).
- The full method set on `LocalAIModel` still matches the `ModelDriver`
interface.
- Pattern parity with the existing Aliyun Rerank
(`internal/entity/models/aliyun.go`) and SiliconFlow Rerank
(`internal/entity/models/siliconflow.go`) implementations.

Closes #14812
Depends on #14809, #14811
Tracking: #14736

Co-authored-by: Jin Hai <[email protected]>
@JinHai-CN JinHai-CN added the ci Continue Integration label May 13, 2026
@JinHai-CN
JinHai-CN marked this pull request as draft May 13, 2026 11:37
@JinHai-CN
JinHai-CN marked this pull request as ready for review May 13, 2026 11:37
@JinHai-CN

Copy link
Copy Markdown
Member

@tmimmanuel The model interface is updated. Would you please also update the PR?

@tmimmanuel

Copy link
Copy Markdown
Contributor Author

@JinHai-CN Thanks for review, I will update now.

@codecov

codecov Bot commented May 13, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (3182fd0) to head (7ec8b5b).
⚠️ Report is 6 commits behind head on main.

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

@tmimmanuel

Copy link
Copy Markdown
Contributor Author

@JinHai-CN Please review.

@JinHai-CN
JinHai-CN merged commit cb01529 into infiniflow:main May 14, 2026
1 check passed
tmimmanuel added a commit to tmimmanuel/ragflow that referenced this pull request May 14, 2026
### What problem does this PR solve?

Add a Go driver for Voyage AI (https://voyageai.com), one of the
unchecked providers on the umbrella tracking issue infiniflow#14736. Voyage AI is
**embed + rerank only** — no chat, no streaming, no `/v1/models`
endpoint. It's the first provider in the Go layer of this shape.

Until this PR, a tenant who configured `voyage` as a model provider in
the Go layer fell through to the default branch of
`internal/entity/models/factory.go` and got the dummy driver.

### What this PR includes

- New `internal/entity/models/voyage.go` with a `VoyageModel`
implementing the `ModelDriver` interface.
- New `conf/models/voyage.json` with 6 embedding models (`voyage-3.5`,
`voyage-3.5-lite`, `voyage-3-large`, `voyage-code-3`, `voyage-law-2`,
`voyage-finance-2`) and 2 rerank models (`rerank-2`, `rerank-2-lite`).
- `factory.go`: route `"voyage"` to `NewVoyageModel`.
- `internal/entity/models/voyage_test.go`: 19 unit tests.

### How the driver works

- **Embed**: `POST /v1/embeddings`. Response is OpenAI-shaped (`{data:
[{embedding, index, object, text}], model, usage}`). Driver reorders by
`index`, rejects duplicate / out-of-range / missing slots, and
short-circuits empty input without an HTTP call.
- **Rerank**: `POST /v1/rerank`. Voyage uses **`top_k`** as the request
param name (not `top_n` like Aliyun/SiliconFlow); the driver translates
`RerankConfig.TopN` → `top_k`. Response is Cohere-shaped (`{data:
[{relevance_score, index}], model}`), so the existing
`RerankResponse{Data: []RerankResult{Index, RelevanceScore}}` shape fits
cleanly.
- **`ListModels`**: returns a hardcoded list of `voyageKnownModels`.
Voyage does **not** expose `/v1/models` (probed live, returns 404), so
the driver synthesizes the list from the same set the config ships. New
upstream models are added by extending one slice.
- **`CheckConnection`**: pings a 1-input embed call against
`voyage-3.5`. Without `/v1/models`, this is the cheapest way to verify
the API key + network path before a tenant tries a real workload.
- **`ChatWithMessages` / `ChatStreamlyWithSender` / `Balance` /
`TranscribeAudio` / `AudioSpeech` / `OCRFile`**: all return `"no such
method"`. Voyage does not host any of these surfaces.

No interface change. No new dependencies.

### How was this tested?

**19 unit tests** in `internal/entity/models/voyage_test.go` — all pass
on go 1.25:

```
$ go test -vet=off -run TestVoyage -count=1 ./internal/entity/models/...
ok      ragflow/internal/entity/models  0.036s
```

Coverage: Name; Embed (happy path, reorder, empty-input, missing
key/model, duplicate index, out-of-range index, missing slot); Rerank
(happy path with `top_k` assertion, default-to-len-documents, empty
documents, out-of-range index); ListModels (static list, missing key);
CheckConnection (happy, 401); chat methods sentinels; Balance sentinel;
audio/OCR sentinels.

`go build ./internal/entity/models/...` exits 0.

**Live integration test** against `api.voyageai.com`:

```
=== RUN   TestVoyageLiveSmoke
    [OK] Name() = "voyage"
    [OK] ListModels (static): 8 models -> [voyage-3.5 voyage-3.5-lite voyage-3-large voyage-code-3 voyage-law-2 voyage-finance-2 rerank-2 rerank-2-lite]
    [OK] CheckConnection
    [OK] Embed vectors=3 dim=1024 indices=[0 1 2]
    [OK] Embed(empty) -> 0 vectors
    [OK] Rerank results=3 scores=[0.8125 0.59765625 0.39453125]
    [OK] ChatWithMessages returns voyage, no such method
    [OK] Balance returns voyage, no such method

VOYAGE LIVE SMOKE PASSED
--- PASS: TestVoyageLiveSmoke (0.81s)
```

What the live run proves on the wire:

- Auth (`Bearer <key>`) accepted by `api.voyageai.com`.
- Embed `voyage-3.5` on 3 inputs returns 3 vectors at dim 1024 with
`index` field preserved as `[0, 1, 2]` — the reorder-by-index code is
exercised on real data.
- Empty input short-circuits without an HTTP call (mock server would
have been hit if it did).
- Rerank `rerank-2` on 3 docs returns 3 real `relevance_score` floats
`[0.8125, 0.598, 0.395]`. The `top_k` translation works on the live
wire.
- All sentinel methods return the documented `"no such method"` strings.

### Note on PR history

This branch was previously named for LocalAI Embed work which is now
consolidated into PR infiniflow#14813. The branch was reset to `upstream/main` and
rebuilt for Voyage. Diff against `main` is a clean +838 lines across 4
files.

### Type of change

- [x] New Feature (non-breaking change which adds functionality)

Tracking: infiniflow#14736

---------

Co-authored-by: Jin Hai <[email protected]>
tmimmanuel added a commit to tmimmanuel/ragflow that referenced this pull request May 14, 2026
Address the two actionable CodeRabbit findings on PR infiniflow#14811:

- voyage.go Embed: trim a trailing slash off baseURL before joining
  with URLSuffix.Embedding, matching what Rerank already does. A
  tenant who configures baseURL as ".../v1/" would otherwise hit
  ".../v1//embeddings" and get a 404.
- voyage.go Rerank: reject duplicate response indices the same way
  Embed does. The earlier code only checked out-of-range; a
  duplicate slot would have silently appended both rows, hiding a
  malformed upstream response.

Tests:
- TestVoyageEmbedTrimsTrailingSlashInBaseURL pins the new behavior.
- TestVoyageRerankRejectsDuplicateIndex mirrors the existing
  TestVoyageEmbedRejectsDuplicateIndex.

Live-verified against api.voyageai.com on the current key: /v1/embeddings
returns OpenAI-shaped data for all six shipped embedding models,
/v1/rerank returns Cohere-shaped data with top_k for both shipped
rerank models, and /v1/models still 404s (justifying the static
ListModels catalog).
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 LocalAI Go driver landed in infiniflow#14809 and Embed landed in infiniflow#14811.
`Rerank` was left as a stub that returns `"not implemented"`. This PR
fills the gap.

LocalAI exposes a public rerank endpoint at `<tenant-url>/v1/rerank`
with a Cohere-shaped request and response (`{model, query, documents,
top_n}` → `{results: [{index, relevance_score}]}`). The Python side has
had `LocalAIRerank` in `rag/llm/rerank_model.py` for a long time. Until
this PR, a tenant who wanted to use LocalAI for reranking in the Go
layer got `"not implemented"`.

### What this PR includes

- `conf/models/localai.json`: add `"rerank": "rerank"` under
`url_suffix` so the driver can build the URL from config. This matches
the `URLSuffix.Rerank` field already used by aliyun and siliconflow.
- `internal/entity/models/localai.go`: replace the `Rerank` stub with a
real implementation that POSTs to `/v1/rerank`. Adds local
request/response types `localAIRerankRequest` and
`localAIRerankResponse`.

No factory change. No interface change.

### How the implementation works

- Validate the model name and resolve the tenant-supplied base URL with
the existing `resolveBaseURL` helper.
- Wrap the request with `context.WithTimeout(nonStreamCallTimeout)` so
the call has a clear deadline. Same pattern `ChatWithMessages`,
`ListModels`, and `Embed` already use in this file.
- Only set the `Authorization` header when a non-empty API key was
supplied. LocalAI accepts an empty key by default, so this preserves the
optional-auth contract.
- Default `top_n` to `len(documents)` when `rerankConfig.TopN == 0`,
matching the existing Aliyun and SiliconFlow rerank implementations.
- Validate every `results[].index` against `len(documents)`. If the
upstream returns an out-of-range index, fail clearly instead of silently
writing past the slice.
- An empty `documents` slice returns `&RerankResponse{}` with no HTTP
call.
- Non-200 responses propagate the upstream status line and body.

### Note on stacking

This PR builds on infiniflow#14809 (LocalAI driver) and infiniflow#14811 (LocalAI Embed).
Until both merge, this PR's diff on GitHub will include all three
commits. After infiniflow#14809 and infiniflow#14811 land on `main`, GitHub will auto-reduce
this PR to only the `Rerank` changes (one commit, ~99 line diff in
`localai.go` plus 1 line in `localai.json`).

### Type of change

- [x] New Feature (non-breaking change which adds functionality)

### How was this tested?

- `go build ./internal/entity/models/...` returns exit 0 on go 1.25 (the
`go.mod` minimum).
- The full method set on `LocalAIModel` still matches the `ModelDriver`
interface.
- Pattern parity with the existing Aliyun Rerank
(`internal/entity/models/aliyun.go`) and SiliconFlow Rerank
(`internal/entity/models/siliconflow.go`) implementations.

Closes infiniflow#14812
Depends on infiniflow#14809, infiniflow#14811
Tracking: infiniflow#14736

Co-authored-by: Jin Hai <[email protected]>
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.

3 participants