Skip to content

Go: implement Rerank in LocalAI driver - #14813

Merged
JinHai-CN merged 2 commits into
infiniflow:mainfrom
tmimmanuel:go/localai-rerank
May 13, 2026
Merged

JinHai-CN merged 2 commits into
infiniflow:mainfrom
tmimmanuel:go/localai-rerank

Conversation

@tmimmanuel

Copy link
Copy Markdown
Contributor

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

  • 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

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

coderabbitai Bot commented May 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

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

Use the following commands to manage reviews:

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

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 5a9d3ca6-f0fd-4f8c-8b39-7fea4aab1334

📥 Commits

Reviewing files that changed from the base of the PR and between 9bebd0e and 6abfc19.

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

📝 Walkthrough

Walkthrough

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

Changes

LocalAI Model Driver

Layer / File(s) Summary
Configuration & Factory Wiring
conf/models/localai.json, internal/entity/models/factory.go
New LocalAI config with URL suffixes and factory case matching "localai" returning NewLocalAIModel.
Driver Type & Initialization
internal/entity/models/localai.go
LocalAIModel type and NewLocalAIModel with HTTP transport, per-instance BaseURL map, and optional Authorization header handling.
Reasoning Helpers & Request Controls
internal/entity/models/localai.go
Helpers to detect/extract LocalAI reasoning fields and inject reasoning_effort / enable_thinking into request bodies.
Chat (non-streaming)
internal/entity/models/localai.go
ChatWithMessages posts stream=false, validates input, forwards generation/reasoning params, parses choices[0].message.content and returns extracted reasoning.
Chat (SSE streaming)
internal/entity/models/localai.go
ChatStreamlyWithSender posts stream=true, parses SSE data: events and [DONE], emits reasoning and content chunks via sender, and cancels on idle timeout.
Embeddings
internal/entity/models/localai.go
Embed posts to embeddings endpoint, optionally sets dimensions, reorders returned vectors by index, and validates completeness and duplicates.
Rerank
internal/entity/models/localai.go
Rerank posts Cohere-shaped rerank request (model, query, documents, top_n), defaults top_n, validates indices, and maps results to RerankResponse.
Model Listing, Balance, Connection
internal/entity/models/localai.go
ListModels parses data[] model ids, Balance returns unsupported error, CheckConnection calls ListModels.
ASR/TTS/OCR stubs
internal/entity/models/localai.go
Adds stubbed ASR/TTS/OCR methods returning "no such method" to satisfy the interface.
Tests
internal/entity/models/localai_test.go
Unit tests for streaming idle watchdog and completion, sender/base-URL/auth header validation, Balance, Embed success/error cases, reasoning extraction, request/stream parameter propagation, and SSE ordering.

Sequence Diagram

sequenceDiagram
  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]"
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related issues

Possibly related PRs

Suggested labels

💞 feature

Suggested reviewers

  • Haruko386

Poem

"I found a tiny endpoint key,
Streams of tokens hopped to me,
Embeddings leapt, rerank did sing,
Tests thumped drums and made me spring,
Rabbit cheers: the driver’s free 🐰"

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Go: implement Rerank in LocalAI driver' clearly and directly describes the primary change in the pull request.
Description check ✅ Passed The PR description fully satisfies the template with all required sections completed: detailed problem statement, explicit type of change selection, implementation approach with code details, and comprehensive testing information.
Linked Issues check ✅ Passed The PR fully implements all coding requirements from issue #14812: Rerank method with POST to /v1/rerank, Cohere-shaped request/response parsing, optional-auth contract, per-call timeout, index validation, and url_suffix config update [#14812].
Out of Scope Changes check ✅ Passed All changes directly support the Rerank implementation objective: config update for url_suffix, localai.go Rerank implementation with request/response types, factory.go support for localai provider, and comprehensive test coverage with no extraneous modifications.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@tmimmanuel
tmimmanuel force-pushed the go/localai-rerank branch from e52be43 to c65d0e0 Compare May 12, 2026 02:20
@tmimmanuel
tmimmanuel force-pushed the go/localai-rerank branch 2 times, most recently from bd4e30a to d6b5249 Compare May 12, 2026 03:12

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

228-313: ⚡ Quick win

Add direct unit tests for LocalAIModel.Rerank semantics introduced by this PR.

This suite is strong for chat/embed, but the new rerank path is still unpinned in unit tests. Please add httptest coverage for: default top_n=len(documents) when zero, empty-doc short-circuit (no HTTP call), optional-auth header behavior, and out-of-range results[].index rejection.

🤖 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

📥 Commits

Reviewing files that changed from the base of the PR and between e52be43 and d6b5249.

📒 Files selected for processing (3)
  • conf/models/localai.json
  • internal/entity/models/localai.go
  • internal/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

Comment thread internal/entity/models/localai.go Resolved
Comment thread internal/entity/models/localai.go Resolved
tmimmanuel added a commit to tmimmanuel/ragflow that referenced this pull request May 12, 2026
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
@tmimmanuel

tmimmanuel commented May 12, 2026 •

Copy link
Copy Markdown
Contributor Author

[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 9bebd0e99)

PR #14813 is now the single consolidated LocalAI PR, rebased cleanly onto upstream/main (no merge conflict, mergeStateStatus: CLEAN). The 11 stacked commits + 1 unrelated Perplexity commit + 3 merge-noise commits from the earlier stack were squashed into one focused change:

$ git diff upstream/main --stat
 conf/models/localai.json               |   8 +
 internal/entity/models/factory.go      |   2 +
 internal/entity/models/localai.go      | 825 +++++++++++++++++++
 internal/entity/models/localai_test.go | 628 ++++++++++++++++
 4 files changed, 1463 insertions(+)

Driver covers:

  • ChatWithMessages non-stream + ChatStreamlyWithSender (SSE) with idle-deadline watchdog, nil-sender guard
  • Embed (/v1/embeddings) with reorder-by-index, empty-input short-circuit, duplicate/out-of-range rejection
  • Rerank (/v1/rerank, Cohere-shaped)
  • ListModels / CheckConnection
  • Multi-field reasoning extraction on both stream and non-stream paths — tries reasoning_content (kimi-k2.6, OpenAI o-series, DeepSeek-R1), then reasoning (Upstage solar-pro3), then thinking (Qwen3). First non-empty wins.
  • Request-side ChatConfig.Effort → reasoning_effort and ChatConfig.Thinking → enable_thinking. Both emitted so the request works against whichever family LocalAI routes to.
  • Optional auth: empty ApiKey → no Authorization header sent (LocalAI's default). Non-empty key → Bearer <key> (proxy auth case).
  • TranscribeAudio / AudioSpeech / OCRFile return "no such method" (matches OpenAI/LM Studio stub style; mapping these to LocalAI's Whisper/TTS backends is a separate piece of work).

Unit tests — 22/22 pass on go 1.25

$ go test -vet=off -run "TestLocalAI|TestExtractLocalAIReasoning" -count=1 -v ./internal/entity/models/...
=== RUN   TestLocalAIName
--- PASS: TestLocalAIName (0.00s)
=== RUN   TestLocalAIStreamCancelsOnIdle
--- PASS: TestLocalAIStreamCancelsOnIdle (0.20s)
=== RUN   TestLocalAIStreamCompletesWithoutTriggeringWatchdog
--- PASS: TestLocalAIStreamCompletesWithoutTriggeringWatchdog (0.00s)
=== RUN   TestLocalAIStreamRequiresSender
--- PASS: TestLocalAIStreamRequiresSender (0.00s)
=== RUN   TestLocalAIChatMissingBaseURLFailsClearly
--- PASS: TestLocalAIChatMissingBaseURLFailsClearly (0.00s)
=== RUN   TestLocalAIChatOmitsAuthHeaderWhenKeyEmpty
--- PASS: TestLocalAIChatOmitsAuthHeaderWhenKeyEmpty (0.00s)
=== RUN   TestLocalAIChatSendsAuthHeaderWhenKeyProvided
--- PASS: TestLocalAIChatSendsAuthHeaderWhenKeyProvided (0.00s)
=== RUN   TestLocalAIBalanceReturnsNoSuchMethod
--- PASS: TestLocalAIBalanceReturnsNoSuchMethod (0.00s)
=== RUN   TestLocalAIEmbedHappyPath
--- PASS: TestLocalAIEmbedHappyPath (0.00s)
=== RUN   TestLocalAIEmbedRejectsDuplicateIndex
--- PASS: TestLocalAIEmbedRejectsDuplicateIndex (0.00s)
=== RUN   TestLocalAIEmbedRejectsOutOfRangeIndex
--- PASS: TestLocalAIEmbedRejectsOutOfRangeIndex (0.00s)
=== RUN   TestLocalAIEmbedRejectsMissingSlot
--- PASS: TestLocalAIEmbedRejectsMissingSlot (0.00s)
=== RUN   TestLocalAIEmbedEmptyInputShortCircuits
--- PASS: TestLocalAIEmbedEmptyInputShortCircuits (0.00s)
=== RUN   TestExtractLocalAIReasoning
=== RUN   TestExtractLocalAIReasoning/empty_map
=== RUN   TestExtractLocalAIReasoning/reasoning_content_wins
=== RUN   TestExtractLocalAIReasoning/reasoning_when_no_reasoning_content
=== RUN   TestExtractLocalAIReasoning/thinking_when_only_that_is_set
=== RUN   TestExtractLocalAIReasoning/empty_string_treated_as_absent
=== RUN   TestExtractLocalAIReasoning/non-string_ignored
--- PASS: TestExtractLocalAIReasoning (0.00s)
    --- PASS: TestExtractLocalAIReasoning/empty_map (0.00s)
    --- PASS: TestExtractLocalAIReasoning/reasoning_content_wins (0.00s)
    --- PASS: TestExtractLocalAIReasoning/reasoning_when_no_reasoning_content (0.00s)
    --- PASS: TestExtractLocalAIReasoning/thinking_when_only_that_is_set (0.00s)
    --- PASS: TestExtractLocalAIReasoning/empty_string_treated_as_absent (0.00s)
    --- PASS: TestExtractLocalAIReasoning/non-string_ignored (0.00s)
=== RUN   TestLocalAIChatExtractsReasoningContent
--- PASS: TestLocalAIChatExtractsReasoningContent (0.01s)
=== RUN   TestLocalAIChatExtractsThinking
--- PASS: TestLocalAIChatExtractsThinking (0.00s)
=== RUN   TestLocalAIChatHandlesAbsentReasoning
--- PASS: TestLocalAIChatHandlesAbsentReasoning (0.00s)
=== RUN   TestLocalAIStreamExtractsReasoningContentDelta
--- PASS: TestLocalAIStreamExtractsReasoningContentDelta (0.00s)
=== RUN   TestLocalAIStreamExtractsThinkingDelta
--- PASS: TestLocalAIStreamExtractsThinkingDelta (0.00s)
=== RUN   TestLocalAIChatPropagatesReasoningEffort
--- PASS: TestLocalAIChatPropagatesReasoningEffort (0.00s)
=== RUN   TestLocalAIChatPropagatesEnableThinking
--- PASS: TestLocalAIChatPropagatesEnableThinking (0.00s)
=== RUN   TestLocalAIStreamPropagatesReasoningParams
--- PASS: TestLocalAIStreamPropagatesReasoningParams (0.00s)
PASS
ok      ragflow/internal/entity/models  0.241s

Live integration — localai/localai:latest-aio-cpu in Docker

Re-ran against the rebased branch state (commit 9bebd0e99) just now to re-confirm. Smoke test file is not committed; it constructs LocalAIModel directly with the URL suffixes that conf/models/localai.json declares and points it at http://localhost:8080/v1.

$ docker run -d -p 8080:8080 localai/localai:latest-aio-cpu   # AIO image, pre-loaded models
$ LOCALAI_URL=http://localhost:8080/v1 \
    go test -vet=off -run TestLocalAILiveSmoke -timeout 300s -v ./internal/entity/models/...

=== RUN   TestLocalAILiveSmoke
    [OK] driver.Name() = "localai"
    [OK] CheckConnection
    [OK] ListModels: 8 models -> [jina-reranker-v1-base-en tts-1 stablediffusion gpt-4 whisper-1 text-embedding-ada-002 silero-vad gpt-4o]
    [OK] Chat answer="pong" reason=""
    [OK] Stream content chunks=9 joined="Hello! How can I help you today?"  reason chunks=0
    [OK] Stream w/ reasoning_effort=high+enable_thinking=true: content=32 reason=0
    [OK] Embed vectors=3 dim=384 indices=[0 1 2]
    [OK] Embed(empty) -> 0 vectors
    [OK] Rerank results=3 scores=[0.03741910681128502 0.036529749631881714 0.030271805822849274]
    [OK] Balance returns no such method
    [OK] TranscribeAudio returns localai, no such method
    [OK] AudioSpeech returns localai, no such method
    [OK] OCRFile returns localai, no such method

LOCALAI LIVE SMOKE PASSED (commit-under-test: build current)
--- PASS: TestLocalAILiveSmoke (49.82s)
PASS
ok  	ragflow/internal/entity/models	49.832s

What this proves on the wire

  • Auth: optional-key contract works — request reaches LocalAI with no Authorization header (the smoke test uses &APIConfig{} — empty key), LocalAI accepts.
  • /v1/models parser handles the real 8-model AIO response.
  • Non-stream chat: POST /v1/chat/completions round-trips correctly, content "pong" extracted, no false reasoning content from the multi-field extractor when none is present.
  • Streaming chat: 9 SSE chunks reconstructed losslessly into "Hello! How can I help you today?" with the new ordering contract (reasoning before content) intact.
  • Streaming with reasoning_effort=high + enable_thinking=true: 32 content chunks. The AIO image's default gpt-4 alias is a non-reasoning local model, so reason chunks stay at 0 — but the request body is accepted, proving non-supporting upstreams ignore the extra fields as designed. The reasoning-extraction code itself is exercised by TestLocalAIChat/StreamExtractsReasoningContentDelta and …ExtractsThinking… against documented kimi-k2.6 and Qwen3 wire shapes.
  • Embed: text-embedding-ada-002 returns 3 vectors at dim 384 with index preserved as [0, 1, 2] — the reorder-by-index code is exercised on real data. Empty-input short-circuit verified (no HTTP call, []EmbeddingData{} returned).
  • Rerank: jina-reranker-v1-base-en returns 3 real relevance_score floats. The Cohere-shaped response parser handles LocalAI's actual /v1/rerank output.
  • All five sentinel methods return "no such method" (Balance, plus the four newly-added Transcribe/AudioSpeech/OCR methods).

What this does NOT prove (and why)

  • The multi-field reasoning extractor (reasoning_content / reasoning / thinking) isn't fired against a live model that emits reasoning, because the AIO image's gpt-4 alias is non-reasoning. The extractor is fully exercised by unit tests against the documented wire shapes for kimi-k2.6, solar-pro3 (reasoning), and Qwen3 (thinking). The Upstage PR fix(upstage): extract reasoning delta from streaming responses #14817 contains a separate live test against solar-pro3 that confirmed the same field-extraction logic works on a real reasoning model.

CodeRabbit feedback addressed

  • json.Unmarshal error handling added to all 3 request-shape tests (TestLocalAIChatPropagatesReasoningEffort, …EnableThinking, …StreamPropagatesReasoningParams). They now surface unmarshal errors with t.Errorf("unmarshal request body: %v\nraw=%s", err, string(raw)) and return instead of silently ignoring.

#14813 stands alone — driver + Embed + Rerank + multi-field reasoning + interface stubs all in one coherent commit on top of upstream/main.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

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

1-605: 🏗️ Heavy lift

Add 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:

  • Embed has 6 tests: happy path, duplicate index, out-of-range index, missing slot, empty input short-circuit, and path validation
  • Chat and ChatStreamly have extensive coverage including reasoning extraction, auth headers, and parameter propagation

Consider adding Rerank unit tests following the same pattern:

  • Happy path: POST to /rerank, parse results[].index and results[].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_n defaults to len(documents) when rerankConfig.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

📥 Commits

Reviewing files that changed from the base of the PR and between d6b5249 and 43f2643.

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

Comment thread internal/entity/models/localai_test.go Resolved
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.
@tmimmanuel
tmimmanuel force-pushed the go/localai-rerank branch from 43f2643 to 9bebd0e Compare May 12, 2026 16:11
tmimmanuel added a commit to tmimmanuel/ragflow that referenced this pull request May 12, 2026
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.
tmimmanuel added a commit to tmimmanuel/ragflow that referenced this pull request May 12, 2026
Voyage AI (https://voyageai.com) is one of the unchecked providers on
the umbrella tracking issue infiniflow#14736. Unlike the other Go drivers, Voyage
is embed/rerank only — no chat, no streaming, no /v1/models endpoint.

What this PR includes:

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

Methods:

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

19 unit tests pass on go 1.25; build clean.

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

Note on PR history: this branch was previously named for LocalAI
Embed work which has since been consolidated into PR infiniflow#14813. The
branch was reset to upstream/main and rebuilt for Voyage — diff is
a clean +800 lines on top of current main.
@tmimmanuel
tmimmanuel requested a review from Haruko386 May 13, 2026 03:31

@Haruko386 Haruko386 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @tmimmanuel LGTM, thank you for your contribution

@Haruko386 Haruko386 added the ci Continue Integration label May 13, 2026
JinHai-CN added a commit that referenced this pull request May 13, 2026
### 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

codecov Bot commented May 13, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (bf90c89) to head (6abfc19).

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@JinHai-CN
JinHai-CN merged commit 0a4b733 into infiniflow:main May 13, 2026
1 check passed
JinHai-CN added a commit that referenced this pull request May 14, 2026
### What problem does this PR solve?

Add a Go driver for Voyage AI (https://voyageai.com), one of the
unchecked providers on the umbrella tracking issue #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]>
tmimmanuel added a commit to tmimmanuel/ragflow that referenced this pull request May 14, 2026
### What problem does this PR solve?

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

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

### What this PR includes

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

### How the driver works

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

No interface change. No new dependencies.

### How was this tested?

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

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

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

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

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

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

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

What the live run proves on the wire:

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

### Note on PR history

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

### Type of change

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

Tracking: infiniflow#14736

---------

Co-authored-by: Jin Hai <[email protected]>
tmimmanuel added a commit to tmimmanuel/ragflow that referenced this pull request May 14, 2026
Voyage AI (https://voyageai.com) is one of the unchecked providers on
the umbrella tracking issue infiniflow#14736. Unlike the other Go drivers, Voyage
is embed/rerank only — no chat, no streaming, no /v1/models endpoint.

What this PR includes:

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

Methods:

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

19 unit tests pass on go 1.25; build clean.

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

Note on PR history: this branch was previously named for LocalAI
Embed work which has since been consolidated into PR infiniflow#14813. The
branch was reset to upstream/main and rebuilt for Voyage — diff is
a clean +800 lines on top of current main.
tmimmanuel added a commit to tmimmanuel/ragflow that referenced this pull request May 14, 2026
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.
@coderabbitai coderabbitai Bot mentioned this pull request May 19, 2026
2 tasks done
JinHai-CN pushed a commit that referenced this pull request May 21, 2026
### 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.
Ricardo-M-L pushed a commit to Ricardo-M-L/ragflow that referenced this pull request Aug 17, 2026
### What problem does this PR solve?

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]>
Ricardo-M-L pushed a commit to Ricardo-M-L/ragflow that referenced this pull request Aug 17, 2026
### What problem does this PR solve?

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

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

### What this PR includes

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

No factory change. No interface change.

### How the implementation works

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

### Note on stacking

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

### Type of change

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

### How was this tested?

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

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

Co-authored-by: Jin Hai <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature Request]: Implement Rerank in the LocalAI Go driver

3 participants