Repository navigation
Go: implement Rerank in LocalAI driver - #14813
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:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughAdds a LocalAI model provider: config and factory wiring, a LocalAIModel driver (chat sync + SSE streaming, embeddings, rerank, model listing, connection checks), reasoning extraction/request controls, ASR/TTS/OCR stubs, and comprehensive unit tests. ChangesLocalAI Model Driver
Sequence DiagramsequenceDiagram
participant Client
participant LocalAIModel
participant TenantLocalAI
Client->>LocalAIModel: POST /v1/chat?stream=true (messages + reasoning params)
LocalAIModel->>TenantLocalAI: HTTP POST to tenant baseURL + chat suffix (optional Authorization)
TenantLocalAI-->>LocalAIModel: SSE stream (data: JSON events / [DONE])
LocalAIModel->>Client: forwards reasoning/content chunks via sender, then "[DONE]"
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related issues
Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 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 |
e52be43 to
c65d0e0
Compare
bd4e30a to
d6b5249
Compare
There was a problem hiding this comment.
🧹 Nitpick comments (1)
internal/entity/models/localai_test.go (1)
228-313: ⚡ Quick winAdd direct unit tests for
LocalAIModel.Reranksemantics introduced by this PR.This suite is strong for chat/embed, but the new rerank path is still unpinned in unit tests. Please add
httptestcoverage for: defaulttop_n=len(documents)when zero, empty-doc short-circuit (no HTTP call), optional-auth header behavior, and out-of-rangeresults[].indexrejection.🤖 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 228 - 313, Add unit tests exercising LocalAIModel.Rerank via the same pattern as existing embedding tests: create httptest servers with handlers validating request path and headers and returning crafted JSON; tests to add: TestLocalAIRerankDefaultTopN (call Rerank with top_n=0 and assert the server sees top_n equal to len(documents) and that returned ordering is used), TestLocalAIRerankEmptyDocsShortCircuits (call Rerank with empty documents and assert no HTTP call is made), TestLocalAIRerankAuthHeaderBehavior (set APIConfig with auth and assert the Authorization header is sent when configured and omitted when not), and TestLocalAIRerankRejectsOutOfRangeIndex (return results[] with index outside documents range and assert Rerank returns an error mentioning out-of-range); use newLocalAIForTest(srv.URL), Rerank method name, and APIConfig to locate the implementation to test and mirror the style of TestLocalAIEmbed* helpers.
🤖 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 228-313: Add unit tests exercising LocalAIModel.Rerank via the
same pattern as existing embedding tests: create httptest servers with handlers
validating request path and headers and returning crafted JSON; tests to add:
TestLocalAIRerankDefaultTopN (call Rerank with top_n=0 and assert the server
sees top_n equal to len(documents) and that returned ordering is used),
TestLocalAIRerankEmptyDocsShortCircuits (call Rerank with empty documents and
assert no HTTP call is made), TestLocalAIRerankAuthHeaderBehavior (set APIConfig
with auth and assert the Authorization header is sent when configured and
omitted when not), and TestLocalAIRerankRejectsOutOfRangeIndex (return results[]
with index outside documents range and assert Rerank returns an error mentioning
out-of-range); use newLocalAIForTest(srv.URL), Rerank method name, and APIConfig
to locate the implementation to test and mirror the style of TestLocalAIEmbed*
helpers.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 68be697a-5310-45c9-8751-5d4f9416ea7c
📒 Files selected for processing (3)
conf/models/localai.jsoninternal/entity/models/localai.gointernal/entity/models/localai_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
- conf/models/localai.json
- internal/entity/models/localai.go
Haruko386 flagged on both infiniflow#14809 and infiniflow#14813 that reasoning traces and thinking output were being silently dropped. LocalAI is a proxy that can route to any model family, and each upstream uses its own field name for the chain-of-thought: - reasoning_content: OpenAI o-series, kimi-k2.6, DeepSeek-R1, magistral when proxied through an OpenAI-shim - reasoning: Upstage solar-pro3 (and proxies) - thinking: Qwen3 (Ollama-style) and some local llama-r1 variants exposed through LocalAI's OpenAI shim The merged driver only read content / delta.content, so for every reasoning-capable model behind LocalAI, the trace never reached ChatResponse.ReasonContent or the streaming sender's reason channel. New helpers extractLocalAIReasoning and addLocalAIReasoningRequestParams keep the priority list in one place (localAIReasoningFields) so adding a new upstream field name is a single-line change. What this changes: - ChatWithMessages: parses message.reasoning_content / reasoning / thinking after content, populates ChatResponse.ReasonContent. Empty string and non-string values are skipped, so non-reasoning models still return empty ReasonContent without erroring (regression-safe). - ChatStreamlyWithSender: same priority order applied to each delta before reading delta.content. Reasoning chunks are emitted via the sender's second arg (the reasonContent channel that the non-stream path already populates), preserving the per-event ordering Upstage and kimi emit on the wire. - Both paths: propagate ChatConfig.Effort -> reasoning_effort and ChatConfig.Thinking -> enable_thinking. LocalAI doesn't know which family it routes to, so emitting both is safe; a non-supporting upstream ignores the extra field. Tests added in internal/entity/models/localai_test.go: - TestExtractLocalAIReasoning: table-driven coverage of the helper (priority order, empty/non-string skip, fallback) - TestLocalAIChatExtractsReasoningContent: kimi-k2.6-style response - TestLocalAIChatExtractsThinking: Qwen3-style response - TestLocalAIChatHandlesAbsentReasoning: non-reasoning regression net - TestLocalAIStreamExtractsReasoningContentDelta: streaming with interleaved delta.reasoning_content and delta.content - TestLocalAIStreamExtractsThinkingDelta: Qwen3 streaming - TestLocalAIChatPropagatesReasoningEffort: Effort -> reasoning_effort - TestLocalAIChatPropagatesEnableThinking: Thinking -> enable_thinking - TestLocalAIStreamPropagatesReasoningParams: stream request All 22 LocalAI tests pass on go 1.25. Build clean. Verified live against localai/localai:latest-aio-cpu in Docker: - ListModels: 8 models - Chat (gpt-4 alias): "pong" - Streaming (gpt-4): 9 chunks, "Hello! How can I help you today?" - Streaming with reasoning_effort=high + enable_thinking=true: request body accepted; non-reasoning AIO models return no reason chunks, proving the params are tolerated by upstreams that ignore them - Embed (text-embedding-ada-002): 3 vectors at dim 384, indices preserved - Rerank (jina-reranker-v1-base-en): 3 results with real relevance scores - Balance: "no such method" (unchanged) - CheckConnection: ok
|
[Edit] Consolidated all live evidence into this single comment so it's easy to re-confirm after the rebase. The earlier text was abbreviated and split across the three LocalAI PRs (#14809 / #14811 / #14813); this is the full picture for the current branch state. What landed (commit
|
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
internal/entity/models/localai_test.go (1)
1-605: 🏗️ Heavy liftAdd unit test coverage for Rerank to match the established testing pattern.
This PR's main feature is implementing
Rerank(per PR title and objectives), yet this test file has no Rerank-specific unit tests. While live integration tests verified Rerank functionality (per PR comments), unit tests would improve maintainability and regression coverage.The file establishes a comprehensive testing pattern for other driver methods:
Embedhas 6 tests: happy path, duplicate index, out-of-range index, missing slot, empty input short-circuit, and path validationChatandChatStreamlyhave extensive coverage including reasoning extraction, auth headers, and parameter propagationConsider adding Rerank unit tests following the same pattern:
- Happy path: POST to
/rerank, parseresults[].indexandresults[].relevance_score- Empty documents: verify short-circuit (no HTTP call)
- Out-of-range index: verify validation error when
results[].index >= len(documents)- Default top_n: verify
top_ndefaults tolen(documents)whenrerankConfig.TopN == 0- Optional auth: verify Authorization header omitted when API key empty
- Error response: verify non-200 status propagation
Would you like me to generate a comprehensive Rerank test suite following the established patterns in this file?
🤖 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 1 - 605, Add unit tests covering the new Rerank method on LocalAIModel: implement tests mirroring the existing patterns (use httptest.NewServer and newLocalAIForTest) including (1) Happy path: POST to "/rerank" returns JSON with results[].index and results[].relevance_score and assert returned ordering and scores; (2) Empty documents short-circuits: call Rerank with empty documents and assert no HTTP call is made; (3) Out-of-range index: server returns a result with index >= len(documents) and assert the method returns an "out of range" error; (4) Default top_n behavior: when rerankConfig.TopN==0 ensure the request body omits/sets top_n to len(documents) and returned results length matches; (5) Optional auth: when APIConfig.ApiKey is nil or empty ensure Authorization header is NOT sent; and (6) non-200 error propagation: server returns non-200 and assert Rerank surfaces the error. Reference the LocalAIModel.Rerank method and use the same test helpers/patterns as tests for Embed and Chat above.
🤖 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_test.go`:
- Around line 525-548: The tests (TestLocalAIChatPropagatesReasoningEffort,
TestLocalAIChatPropagatesEnableThinking,
TestLocalAIStreamPropagatesReasoningParams) currently ignore the error returned
by json.Unmarshal when populating the handler-local `seen` map; modify each
handler to capture the unmarshal error (e.g., err := json.Unmarshal(raw, &seen))
and fail the test immediately with t.Fatalf("json.Unmarshal: %v", err) (or
similar) so JSON parse failures surface clearly instead of causing confusing
downstream assertions; update the anonymous http.HandlerFunc bodies in those
tests to perform this check.
---
Nitpick comments:
In `@internal/entity/models/localai_test.go`:
- Around line 1-605: Add unit tests covering the new Rerank method on
LocalAIModel: implement tests mirroring the existing patterns (use
httptest.NewServer and newLocalAIForTest) including (1) Happy path: POST to
"/rerank" returns JSON with results[].index and results[].relevance_score and
assert returned ordering and scores; (2) Empty documents short-circuits: call
Rerank with empty documents and assert no HTTP call is made; (3) Out-of-range
index: server returns a result with index >= len(documents) and assert the
method returns an "out of range" error; (4) Default top_n behavior: when
rerankConfig.TopN==0 ensure the request body omits/sets top_n to len(documents)
and returned results length matches; (5) Optional auth: when APIConfig.ApiKey is
nil or empty ensure Authorization header is NOT sent; and (6) non-200 error
propagation: server returns non-200 and assert Rerank surfaces the error.
Reference the LocalAIModel.Rerank method and use the same test helpers/patterns
as tests for Embed and Chat above.
🪄 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: d2113e86-21da-4d99-88f2-ab39896f4d0f
📒 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
LocalAI (https://localai.io) is a self-hosted OpenAI-compatible inference server. This PR ships the full driver: - ChatWithMessages non-streaming chat completions - ChatStreamlyWithSender SSE streaming with idle-deadline watchdog, nil-sender guard, and clean-error surfacing when the upstream stalls mid-body - Embed OpenAI-compatible /v1/embeddings, with reorder-by-index, empty-input short-circuit, and duplicate/out-of-range rejection - Rerank Cohere-shaped /v1/rerank - ListModels / CheckConnection - Multi-field reasoning extraction (reasoning_content / reasoning / thinking) on both stream and non-stream paths so models behind a LocalAI proxy (kimi-k2.6, Upstage solar-pro3 via OpenAI-shim, Qwen3, DeepSeek-R1) all surface their chain-of-thought as ChatResponse.ReasonContent - Request-side propagation of ChatConfig.Effort -> reasoning_effort and ChatConfig.Thinking -> enable_thinking; non-supporting upstreams ignore the extra fields - Optional auth: LocalAI accepts an empty API key by default; the driver only sets Authorization when a non-empty key was supplied, so tenants behind an auth proxy can still use a token while bare local instances work without one Self-hosted constraints: - conf/models/localai.json has no `url.default` and no hardcoded model list — the tenant supplies both, same shape as the lmstudio and vllm configs - resolveBaseURL fails fast with a helpful "configure the local access address" message when neither the requested region nor the "default" entry is set Audio / OCR methods (TranscribeAudio, AudioSpeech, OCRFile) added by the ModelDriver interface update return "no such method"; mapping those to LocalAI's Whisper / TTS backends is a separate piece of work. Tests in internal/entity/models/localai_test.go (22 tests): - TestLocalAIName, ChatMissingBaseURL, ChatOmits/SendsAuthHeader - TestLocalAIStreamCancelsOnIdle (watchdog), TestLocalAIStreamCompletesWithoutTriggeringWatchdog, TestLocalAIStreamRequiresSender - TestLocalAIEmbed{HappyPath,RejectsDuplicateIndex, RejectsOutOfRangeIndex,RejectsMissingSlot,EmptyInputShortCircuits} - TestLocalAIBalanceReturnsNoSuchMethod - TestExtractLocalAIReasoning (table-driven helper coverage) - TestLocalAIChat{ExtractsReasoningContent,ExtractsThinking, HandlesAbsentReasoning} - TestLocalAIStream{ExtractsReasoningContentDelta, ExtractsThinkingDelta} - TestLocalAIChat{PropagatesReasoningEffort,PropagatesEnableThinking} - TestLocalAIStreamPropagatesReasoningParams All 22 pass on go 1.25. Build clean. Verified live against localai/localai:latest-aio-cpu in Docker: ListModels 8 ids; Chat "pong"; Stream 9 chunks; Stream with reasoning_effort=high+enable_thinking=true 32 content chunks (non-reasoning upstream tolerates the extra params, as designed); Embed 3 vectors at dim 384 with order preserved; Rerank 3 results with real relevance scores.
43f2643 to
9bebd0e
Compare
LongCat (Meituan, https://longcat.chat) is one of the unchecked providers on the umbrella tracking issue infiniflow#14736. Its API is OpenAI-compatible at https://api.longcat.chat/openai/v1 with three public chat models: LongCat-Flash-Chat, LongCat-Flash-Lite, and LongCat-Flash-Thinking (a reasoning model). What this PR includes: - internal/entity/models/longcat.go: full driver implementing the ModelDriver interface - conf/models/longcat.json: base URL + url_suffix + the 3 public models - factory.go: route "longcat" provider name to NewLongCatModel - internal/entity/models/longcat_test.go: 21 unit tests Methods: - ChatWithMessages non-stream chat - ChatStreamlyWithSender SSE streaming chat - ListModels / CheckConnection - reasoning_content extraction on both stream and non-stream paths (LongCat-Flash-Thinking returns the chain-of-thought in message.reasoning_content / delta.reasoning_content, OpenAI o-series shape; live-probed before writing tests) - reasoning_effort propagation from ChatConfig.Effort - Embed / Rerank / Balance / TranscribeAudio / AudioSpeech / OCRFile return the "no such method" sentinel (LongCat does not expose any of these surfaces) Pattern parity with the merged Mistral (infiniflow#14807), Upstage (infiniflow#14819), and StepFun (infiniflow#14815) drivers. No interface change. Verified live against api.longcat.chat: - ListModels: 5 ids (Flash-Lite, Flash-Chat, Flash-Thinking-2601, Flash-Omni-2603, 2.0-Preview) - Chat (Flash-Chat) non-stream: "Got it! Let me know if you..." - Chat (Flash-Thinking) non-stream: 443-char answer + 557-char reasoning trace extracted into ChatResponse.ReasonContent - Stream (Flash-Thinking): 78 content chunks (351 chars) + 107 reasoning chunks (537 chars) — the delta.reasoning_content extraction works end to end against real wire data - Sentinels all return "no such method" 21 unit tests pass on go 1.25; build clean. Note on PR history: this branch was previously named for LocalAI work which has since been consolidated into PR infiniflow#14813. The branch was reset to upstream/main and rebuilt for LongCat — diff is a clean +1052 lines on top of current main.
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.
Haruko386
left a comment
There was a problem hiding this comment.
Hi @tmimmanuel LGTM, thank you for your contribution
### What problem does this PR solve? Add a Go driver for LongCat (Meituan, https://longcat.chat), one of the unchecked providers on the umbrella tracking issue #14736. LongCat exposes an OpenAI-compatible REST API at `https://api.longcat.chat/openai/v1` with three public chat models including `LongCat-Flash-Thinking`, a reasoning model that returns chain-of-thought in `reasoning_content` (OpenAI o-series shape). Until this PR, a tenant who configured `longcat` 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/longcat.go` with a `LongCatModel` implementing the `ModelDriver` interface. - New `conf/models/longcat.json` with the 3 public chat models (Flash-Chat, Flash-Lite, Flash-Thinking) and `url_suffix` for `chat` and `models`. - `factory.go`: route `"longcat"` to `NewLongCatModel`. Method coverage: - `ChatWithMessages`: `POST /openai/v1/chat/completions`, non-streaming - `ChatStreamlyWithSender`: SSE stream against the same endpoint - `ListModels` / `CheckConnection`: `GET /openai/v1/models` - **Reasoning extraction**: `message.reasoning_content` (non-stream) and `delta.reasoning_content` (stream) flow into `ChatResponse.ReasonContent` / the sender's second arg. Matches the OpenAI o-series convention also used by kimi-k2.6 and DeepSeek-R1. - **`reasoning_effort` propagation**: `ChatConfig.Effort` → request body `reasoning_effort` (LongCat-Flash-Thinking honors it; non-reasoning models ignore it). - `Embed` / `Rerank` / `Balance` / `TranscribeAudio` / `AudioSpeech` / `OCRFile` return `"no such method"` (LongCat does not expose any of these surfaces). No interface change. No new dependencies. ### How was this tested? **21 unit tests** in `internal/entity/models/longcat_test.go` — all pass: ``` $ go test -vet=off -run TestLongCat -count=1 -v ./internal/entity/models/... === RUN TestLongCatName --- PASS: TestLongCatName (0.00s) === RUN TestLongCatChatHappyPath --- PASS: TestLongCatChatHappyPath (0.00s) === RUN TestLongCatChatExtractsReasoningContent --- PASS: TestLongCatChatExtractsReasoningContent (0.00s) === RUN TestLongCatChatPropagatesReasoningEffort --- PASS: TestLongCatChatPropagatesReasoningEffort (0.00s) === RUN TestLongCatChatOmitsReasoningEffortWhenUnset --- PASS: TestLongCatChatOmitsReasoningEffortWhenUnset (0.00s) === RUN TestLongCatChatRequiresAPIKey --- PASS: TestLongCatChatRequiresAPIKey (0.00s) === RUN TestLongCatChatRequiresMessages --- PASS: TestLongCatChatRequiresMessages (0.00s) === RUN TestLongCatChatRejectsHTTPError --- PASS: TestLongCatChatRejectsHTTPError (0.00s) === RUN TestLongCatStreamHappyPath --- PASS: TestLongCatStreamHappyPath (0.00s) === RUN TestLongCatStreamExtractsReasoningContent --- PASS: TestLongCatStreamExtractsReasoningContent (0.00s) === RUN TestLongCatStreamRejectsExplicitFalse --- PASS: TestLongCatStreamRejectsExplicitFalse (0.00s) === RUN TestLongCatStreamRequiresSender --- PASS: TestLongCatStreamRequiresSender (0.00s) === RUN TestLongCatStreamFailsWithoutTerminal --- PASS: TestLongCatStreamFailsWithoutTerminal (0.00s) === RUN TestLongCatListModelsHappyPath --- PASS: TestLongCatListModelsHappyPath (0.00s) === RUN TestLongCatListModelsRequiresAPIKey --- PASS: TestLongCatListModelsRequiresAPIKey (0.00s) === RUN TestLongCatCheckConnectionDelegatesToListModels --- PASS: TestLongCatCheckConnectionDelegatesToListModels (0.00s) === RUN TestLongCatEmbedReturnsNoSuchMethod --- PASS: TestLongCatEmbedReturnsNoSuchMethod (0.00s) === RUN TestLongCatRerankReturnsNoSuchMethod --- PASS: TestLongCatRerankReturnsNoSuchMethod (0.00s) === RUN TestLongCatBalanceReturnsNoSuchMethod --- PASS: TestLongCatBalanceReturnsNoSuchMethod (0.00s) === RUN TestLongCatAudioOCRReturnNoSuchMethod --- PASS: TestLongCatAudioOCRReturnNoSuchMethod (0.00s) PASS ok ragflow/internal/entity/models 0.020s ``` `go build ./internal/entity/models/...` exits 0 on go 1.25. **Live integration test** against `api.longcat.chat`: ``` === RUN TestLongCatLiveSmoke [OK] Name() = "longcat" [OK] CheckConnection [OK] ListModels: 5 models -> [LongCat-Flash-Lite LongCat-Flash-Chat LongCat-Flash-Thinking-2601 LongCat-Flash-Omni-2603 LongCat-2.0-Preview] [OK] Chat (Flash-Chat) answer="Got it! Let me know if you" reason="" [OK] Chat (Flash-Thinking) answer len=443 head="To find 15 % of 80, follow these steps:\n\n1. **Convert the percentage to a frac..." ReasonContent len=557 head="The user asks: \"15% of 80?\" They want step by step reasoning and final answer in \\boxed{}. So we need to compute 15% of ..." [OK] Stream content: 78 chunks, 351 chars [OK] Stream reasoning: 107 chunks, 537 chars [OK] Balance returns longcat, no such method [OK] Embed returns longcat, no such method [OK] Rerank returns longcat, no such method LONGCAT LIVE SMOKE PASSED --- PASS: TestLongCatLiveSmoke (31.01s) ``` What the live run proves on the wire: - Auth header (`Bearer <key>`) is accepted by `api.longcat.chat`. - `/openai/v1/models` parser handles the real 5-model response (note: live API returns versioned aliases `LongCat-Flash-Thinking-2601`, `LongCat-Flash-Omni-2603`, `LongCat-2.0-Preview` plus the un-versioned `LongCat-Flash-Chat` and `LongCat-Flash-Lite`). - Non-stream chat against `LongCat-Flash-Chat`: visible answer parses correctly, `ReasonContent` correctly empty. - Non-stream chat against `LongCat-Flash-Thinking`: 443-char answer flows into `Answer`, 557-char chain-of-thought flows into `ReasonContent` via the new `message.reasoning_content` extraction. - Streaming chat against `LongCat-Flash-Thinking`: 107 reasoning chunks (537 chars) reach the sender's second arg via `delta.reasoning_content`; 78 content chunks (351 chars) reach the first arg. Before this code, the reasoning chunks would have been silently dropped. - All sentinel methods (Balance, Embed, Rerank, audio/OCR) return the documented `"no such method"` strings. ### Note on PR history This branch was previously named for LocalAI work which is now consolidated into PR #14813. The branch was reset to `upstream/main` and rebuilt for LongCat. The diff against `main` is a clean +969 lines across 4 files. ### Type of change - [x] New Feature (non-breaking change which adds functionality) Tracking: #14736 --------- Co-authored-by: Jin Hai <[email protected]>
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14813 +/- ##
=======================================
Coverage 94.16% 94.16%
=======================================
Files 10 10
Lines 703 703
Branches 112 112
=======================================
Hits 662 662
Misses 25 25
Partials 16 16 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
### What problem does this PR solve? 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 - [x] New Feature (non-breaking change which adds functionality) Tracking: #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 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]>
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.
LongCat (Meituan, https://longcat.chat) is one of the unchecked providers on the umbrella tracking issue infiniflow#14736. Its API is OpenAI-compatible at https://api.longcat.chat/openai/v1 with three public chat models: LongCat-Flash-Chat, LongCat-Flash-Lite, and LongCat-Flash-Thinking (a reasoning model). What this PR includes: - internal/entity/models/longcat.go: full driver implementing the ModelDriver interface - conf/models/longcat.json: base URL + url_suffix + the 3 public models - factory.go: route "longcat" provider name to NewLongCatModel - internal/entity/models/longcat_test.go: 21 unit tests Methods: - ChatWithMessages non-stream chat - ChatStreamlyWithSender SSE streaming chat - ListModels / CheckConnection - reasoning_content extraction on both stream and non-stream paths (LongCat-Flash-Thinking returns the chain-of-thought in message.reasoning_content / delta.reasoning_content, OpenAI o-series shape; live-probed before writing tests) - reasoning_effort propagation from ChatConfig.Effort - Embed / Rerank / Balance / TranscribeAudio / AudioSpeech / OCRFile return the "no such method" sentinel (LongCat does not expose any of these surfaces) Pattern parity with the merged Mistral (infiniflow#14807), Upstage (infiniflow#14819), and StepFun (infiniflow#14815) drivers. No interface change. Verified live against api.longcat.chat: - ListModels: 5 ids (Flash-Lite, Flash-Chat, Flash-Thinking-2601, Flash-Omni-2603, 2.0-Preview) - Chat (Flash-Chat) non-stream: "Got it! Let me know if you..." - Chat (Flash-Thinking) non-stream: 443-char answer + 557-char reasoning trace extracted into ChatResponse.ReasonContent - Stream (Flash-Thinking): 78 content chunks (351 chars) + 107 reasoning chunks (537 chars) — the delta.reasoning_content extraction works end to end against real wire data - Sentinels all return "no such method" 21 unit tests pass on go 1.25; build clean. Note on PR history: this branch was previously named for LocalAI work which has since been consolidated into PR infiniflow#14813. The branch was reset to upstream/main and rebuilt for LongCat — diff is a clean +1052 lines on top of current main.
### What problem does this PR solve? Fixes #14816 The Xinference Go driver landed chat in #14938 and Embed is in review in #14932, but `Rerank` shipped as a stub that returns `"xinference, no such method"`. Tenants who launch a rerank model with `--model-type rerank` on their Xinference instance cannot route it through the Go API server. This PR fills the gap. Xinference exposes an OpenAI-compatible REST API. The rerank endpoint is at `POST <base>/v1/rerank` and accepts the Cohere-shaped body `{model, query, documents, top_n}`, returning `{results: [{index, relevance_score}]}` — the same wire shape used by the merged NVIDIA (#14778), Aliyun (#14676), Gitee (#14656), ZhipuAI (#14608), Novita (#15014), and LocalAI (#14813) Rerank implementations. Documented in [Xinference rerank docs](https://inference.readthedocs.io/en/v1.6.1/models/model_abilities/rerank.html); the [builtin rerank model catalog](https://inference.readthedocs.io/en/stable/models/builtin/rerank/) lists `bge-reranker-base`, `bge-reranker-large`, `bge-reranker-v2-m3`, and others.
### What problem does this PR solve? Add a Go driver for LongCat (Meituan, https://longcat.chat), one of the unchecked providers on the umbrella tracking issue infiniflow#14736. LongCat exposes an OpenAI-compatible REST API at `https://api.longcat.chat/openai/v1` with three public chat models including `LongCat-Flash-Thinking`, a reasoning model that returns chain-of-thought in `reasoning_content` (OpenAI o-series shape). Until this PR, a tenant who configured `longcat` 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/longcat.go` with a `LongCatModel` implementing the `ModelDriver` interface. - New `conf/models/longcat.json` with the 3 public chat models (Flash-Chat, Flash-Lite, Flash-Thinking) and `url_suffix` for `chat` and `models`. - `factory.go`: route `"longcat"` to `NewLongCatModel`. Method coverage: - `ChatWithMessages`: `POST /openai/v1/chat/completions`, non-streaming - `ChatStreamlyWithSender`: SSE stream against the same endpoint - `ListModels` / `CheckConnection`: `GET /openai/v1/models` - **Reasoning extraction**: `message.reasoning_content` (non-stream) and `delta.reasoning_content` (stream) flow into `ChatResponse.ReasonContent` / the sender's second arg. Matches the OpenAI o-series convention also used by kimi-k2.6 and DeepSeek-R1. - **`reasoning_effort` propagation**: `ChatConfig.Effort` → request body `reasoning_effort` (LongCat-Flash-Thinking honors it; non-reasoning models ignore it). - `Embed` / `Rerank` / `Balance` / `TranscribeAudio` / `AudioSpeech` / `OCRFile` return `"no such method"` (LongCat does not expose any of these surfaces). No interface change. No new dependencies. ### How was this tested? **21 unit tests** in `internal/entity/models/longcat_test.go` — all pass: ``` $ go test -vet=off -run TestLongCat -count=1 -v ./internal/entity/models/... === RUN TestLongCatName --- PASS: TestLongCatName (0.00s) === RUN TestLongCatChatHappyPath --- PASS: TestLongCatChatHappyPath (0.00s) === RUN TestLongCatChatExtractsReasoningContent --- PASS: TestLongCatChatExtractsReasoningContent (0.00s) === RUN TestLongCatChatPropagatesReasoningEffort --- PASS: TestLongCatChatPropagatesReasoningEffort (0.00s) === RUN TestLongCatChatOmitsReasoningEffortWhenUnset --- PASS: TestLongCatChatOmitsReasoningEffortWhenUnset (0.00s) === RUN TestLongCatChatRequiresAPIKey --- PASS: TestLongCatChatRequiresAPIKey (0.00s) === RUN TestLongCatChatRequiresMessages --- PASS: TestLongCatChatRequiresMessages (0.00s) === RUN TestLongCatChatRejectsHTTPError --- PASS: TestLongCatChatRejectsHTTPError (0.00s) === RUN TestLongCatStreamHappyPath --- PASS: TestLongCatStreamHappyPath (0.00s) === RUN TestLongCatStreamExtractsReasoningContent --- PASS: TestLongCatStreamExtractsReasoningContent (0.00s) === RUN TestLongCatStreamRejectsExplicitFalse --- PASS: TestLongCatStreamRejectsExplicitFalse (0.00s) === RUN TestLongCatStreamRequiresSender --- PASS: TestLongCatStreamRequiresSender (0.00s) === RUN TestLongCatStreamFailsWithoutTerminal --- PASS: TestLongCatStreamFailsWithoutTerminal (0.00s) === RUN TestLongCatListModelsHappyPath --- PASS: TestLongCatListModelsHappyPath (0.00s) === RUN TestLongCatListModelsRequiresAPIKey --- PASS: TestLongCatListModelsRequiresAPIKey (0.00s) === RUN TestLongCatCheckConnectionDelegatesToListModels --- PASS: TestLongCatCheckConnectionDelegatesToListModels (0.00s) === RUN TestLongCatEmbedReturnsNoSuchMethod --- PASS: TestLongCatEmbedReturnsNoSuchMethod (0.00s) === RUN TestLongCatRerankReturnsNoSuchMethod --- PASS: TestLongCatRerankReturnsNoSuchMethod (0.00s) === RUN TestLongCatBalanceReturnsNoSuchMethod --- PASS: TestLongCatBalanceReturnsNoSuchMethod (0.00s) === RUN TestLongCatAudioOCRReturnNoSuchMethod --- PASS: TestLongCatAudioOCRReturnNoSuchMethod (0.00s) PASS ok ragflow/internal/entity/models 0.020s ``` `go build ./internal/entity/models/...` exits 0 on go 1.25. **Live integration test** against `api.longcat.chat`: ``` === RUN TestLongCatLiveSmoke [OK] Name() = "longcat" [OK] CheckConnection [OK] ListModels: 5 models -> [LongCat-Flash-Lite LongCat-Flash-Chat LongCat-Flash-Thinking-2601 LongCat-Flash-Omni-2603 LongCat-2.0-Preview] [OK] Chat (Flash-Chat) answer="Got it! Let me know if you" reason="" [OK] Chat (Flash-Thinking) answer len=443 head="To find 15 % of 80, follow these steps:\n\n1. **Convert the percentage to a frac..." ReasonContent len=557 head="The user asks: \"15% of 80?\" They want step by step reasoning and final answer in \\boxed{}. So we need to compute 15% of ..." [OK] Stream content: 78 chunks, 351 chars [OK] Stream reasoning: 107 chunks, 537 chars [OK] Balance returns longcat, no such method [OK] Embed returns longcat, no such method [OK] Rerank returns longcat, no such method LONGCAT LIVE SMOKE PASSED --- PASS: TestLongCatLiveSmoke (31.01s) ``` What the live run proves on the wire: - Auth header (`Bearer <key>`) is accepted by `api.longcat.chat`. - `/openai/v1/models` parser handles the real 5-model response (note: live API returns versioned aliases `LongCat-Flash-Thinking-2601`, `LongCat-Flash-Omni-2603`, `LongCat-2.0-Preview` plus the un-versioned `LongCat-Flash-Chat` and `LongCat-Flash-Lite`). - Non-stream chat against `LongCat-Flash-Chat`: visible answer parses correctly, `ReasonContent` correctly empty. - Non-stream chat against `LongCat-Flash-Thinking`: 443-char answer flows into `Answer`, 557-char chain-of-thought flows into `ReasonContent` via the new `message.reasoning_content` extraction. - Streaming chat against `LongCat-Flash-Thinking`: 107 reasoning chunks (537 chars) reach the sender's second arg via `delta.reasoning_content`; 78 content chunks (351 chars) reach the first arg. Before this code, the reasoning chunks would have been silently dropped. - All sentinel methods (Balance, Embed, Rerank, audio/OCR) return the documented `"no such method"` strings. ### Note on PR history This branch was previously named for LocalAI work which is now consolidated into PR infiniflow#14813. The branch was reset to `upstream/main` and rebuilt for LongCat. The diff against `main` is a clean +969 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]>
### 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?
The LocalAI Go driver landed in #14809 and Embed landed in #14811.
Rerankwas left as a stub that returns"not implemented". This PR fills the gap.LocalAI exposes a public rerank endpoint at
<tenant-url>/v1/rerankwith a Cohere-shaped request and response ({model, query, documents, top_n}→{results: [{index, relevance_score}]}). The Python side has hadLocalAIRerankinrag/llm/rerank_model.pyfor 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"underurl_suffixso the driver can build the URL from config. This matches theURLSuffix.Rerankfield already used by aliyun and siliconflow.internal/entity/models/localai.go: replace theRerankstub with a real implementation that POSTs to/v1/rerank. Adds local request/response typeslocalAIRerankRequestandlocalAIRerankResponse.No factory change. No interface change.
How the implementation works
resolveBaseURLhelper.context.WithTimeout(nonStreamCallTimeout)so the call has a clear deadline. Same patternChatWithMessages,ListModels, andEmbedalready use in this file.Authorizationheader when a non-empty API key was supplied. LocalAI accepts an empty key by default, so this preserves the optional-auth contract.top_ntolen(documents)whenrerankConfig.TopN == 0, matching the existing Aliyun and SiliconFlow rerank implementations.results[].indexagainstlen(documents). If the upstream returns an out-of-range index, fail clearly instead of silently writing past the slice.documentsslice returns&RerankResponse{}with no HTTP call.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 theRerankchanges (one commit, ~99 line diff inlocalai.goplus 1 line inlocalai.json).Type of change
How was this tested?
go build ./internal/entity/models/...returns exit 0 on go 1.25 (thego.modminimum).LocalAIModelstill matches theModelDriverinterface.internal/entity/models/aliyun.go) and SiliconFlow Rerank (internal/entity/models/siliconflow.go) implementations.Closes #14812
Depends on #14809, #14811
Tracking: #14736