Repository navigation
Go: implement provider: Voyage AI - #14811
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThis 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. ChangesVoyage AI Model Driver
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)
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)
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related issues
Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 1 | ❌ 4❌ Failed checks (4 warnings)
✅ Passed checks (1 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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
📒 Files selected for processing (3)
conf/models/localai.jsoninternal/entity/models/factory.gointernal/entity/models/localai.go
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.
9b528d1 to
c72f278
Compare
c72f278 to
f08a7ef
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
internal/entity/models/localai_test.go (1)
13-226: ⚡ Quick winAdd unit coverage for the new
Embedpath.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[*].indexresponses soEmbed'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
📒 Files selected for processing (3)
conf/models/localai.jsoninternal/entity/models/localai.gointernal/entity/models/localai_test.go
✅ Files skipped from review due to trivial changes (1)
- conf/models/localai.json
There was a problem hiding this comment.
🧹 Nitpick comments (1)
internal/entity/models/localai_test.go (1)
51-56: ⚡ Quick winSimplify 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.Cleanupruns in LIFO order, so registeringsrv.Closefirst (line 74) andclose(hold)second (line 75) ensuresclose(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
📒 Files selected for processing (2)
internal/entity/models/localai.gointernal/entity/models/localai_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
- internal/entity/models/localai.go
|
Duplicated with #14813. I will close it. Please feel free to re-open it, if i am wrong. |
7390d95 to
5e46457
Compare
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.
There was a problem hiding this comment.
🧹 Nitpick comments (2)
internal/entity/models/voyage.go (2)
307-316: 💤 Low valueConsider 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 winInconsistent 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'sbaseURLends with a trailing slash andURLSuffix.Embeddingdoes 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
📒 Files selected for processing (4)
conf/models/voyage.jsoninternal/entity/models/factory.gointernal/entity/models/voyage.gointernal/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).
|
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:
Both are pinned by tests ( Docs vs code audit:
Optional documented fields ( Live re-test against api.voyageai.com on 094e213: 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
left a comment
There was a problem hiding this comment.
Hi @tmimmanuel, Embed and Rerank is OK
plz change what I me mentioned
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.
|
@Haruko386 thanks — pushed 2c0a1b6 with the max_tokens corrections.
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:
Tests still pass (16 covering Embed/Rerank wire shape + URL trim). |
Haruko386
left a comment
There was a problem hiding this comment.
@tmimmanuel Thank you for your contribution
### 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]>
|
@tmimmanuel The model interface is updated. Would you please also update the PR? |
|
@JinHai-CN Thanks for review, I will update now. |
# Conflicts: # internal/entity/models/localai.go
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
|
@JinHai-CN Please review. |
### 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]>
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).
### 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]>
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/modelsendpoint. It's the first provider in the Go layer of this shape.Until this PR, a tenant who configured
voyageas a model provider in the Go layer fell through to the default branch ofinternal/entity/models/factory.goand got the dummy driver.What this PR includes
internal/entity/models/voyage.gowith aVoyageModelimplementing theModelDriverinterface.conf/models/voyage.jsonwith 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"toNewVoyageModel.internal/entity/models/voyage_test.go: 19 unit tests.How the driver works
POST /v1/embeddings. Response is OpenAI-shaped ({data: [{embedding, index, object, text}], model, usage}). Driver reorders byindex, rejects duplicate / out-of-range / missing slots, and short-circuits empty input without an HTTP call.POST /v1/rerank. Voyage usestop_kas the request param name (nottop_nlike Aliyun/SiliconFlow); the driver translatesRerankConfig.TopN→top_k. Response is Cohere-shaped ({data: [{relevance_score, index}], model}), so the existingRerankResponse{Data: []RerankResult{Index, RelevanceScore}}shape fits cleanly.ListModels: returns a hardcoded list ofvoyageKnownModels. 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 againstvoyage-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:Coverage: Name; Embed (happy path, reorder, empty-input, missing key/model, duplicate index, out-of-range index, missing slot); Rerank (happy path with
top_kassertion, 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:What the live run proves on the wire:
Bearer <key>) accepted byapi.voyageai.com.voyage-3.5on 3 inputs returns 3 vectors at dim 1024 withindexfield preserved as[0, 1, 2]— the reorder-by-index code is exercised on real data.rerank-2on 3 docs returns 3 realrelevance_scorefloats[0.8125, 0.598, 0.395]. Thetop_ktranslation works on the live wire."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/mainand rebuilt for Voyage. Diff againstmainis a clean +838 lines across 4 files.Type of change
Tracking: #14736